soarli

ubuntu运行sh脚本sudo自动输入密码
以如下代码为例sudo apt-get update第一种方法使用管道(上一个命令的 stdout 接到下一个命令...
扫描右侧二维码阅读全文
31
2020/01

ubuntu运行sh脚本sudo自动输入密码

以如下代码为例

sudo apt-get update

第一种方法

使用管道(上一个命令的 stdout 接到下一个命令的 stdin):

#!/bin/bash
echo password | sudo -S apt-get update

第二种方法

使用文本块输入重定向:

#!/bin/bash
sudo -S apt-get update << EOF 
你的密码
EOF

说明:

在shell脚本中,通常将EOF与 << 结合使用,表示后续的输入作为子命令或子Shell的输入,直到遇到EOF为止,再返回到主Shell,即将‘你的密码’当做命令的输入

-S参数的作用

使用man命令查询sudo,对参数-S的说明如下:

Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.

可见加上-S参数sudo才会从标准输入中读取密码,不加-S参数以上命令将起不到作用

原文地址:

https://segmentfault.com/a/1190000004950264

最后修改:2020 年 04 月 01 日 10 : 13 PM

发表评论