ubuntu/linux运行shell脚本sudo自动输入密码(亲测可以)

  • 运行如下代码为例
    sudo apt-get update

     

  •  第一种方法

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

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

     

  • 第二种方法

    使用文本块输入重定向:

    #!/bin/bash
    sudo -S apt-get update << EOF 
    yourpassword
    EOF
     

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

  • -S参数的作用

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值