How to pass the password to su/sudo/ssh without ov

2018-12-31 19:07发布

I'm writing a C Shell program that will be doing su or sudo or ssh. They all want their passwords in console input (the TTY) rather than stdin or the command line.

Does anybody know a solution?

Setting up password-less sudo is not an option.

could be an option, but it's not present on my stripped-down system.

20条回答
人气声优
2楼-- · 2018-12-31 19:15

You can provide password as parameter to expect script.

查看更多
步步皆殇っ
3楼-- · 2018-12-31 19:17

Set SSH up for Public Key Authentication, with no pasphrase on the Key. Loads of guides on the net. You won't need a password to login then. You can then limit connections for a key based on client hostname. Provides reasonable security and is great for automated logins.

查看更多
听够珍惜
4楼-- · 2018-12-31 19:22

This can be done by setting up public/private keys on the target hosts you will be connecting to. The first step would be to generate an ssh key for the user running the script on the local host, by executing:

ssh-keygen
Enter file in which to save the key (/home/myuser/.ssh/id_rsa): <Hit enter for default>
Overwrite (y/n)? y

Then enter a blank password. After that, copy your ssh key onto the target host which you will be connecting to.

ssh-copy-id <remote_user>@<other_host>
remote_user@other_host's password: <Enter remote user's password here>

After registering the ssh keys, you would be able to perform a silent ssh remote_user@other_host from you local host.

查看更多
不再属于我。
5楼-- · 2018-12-31 19:22

Maybe you can use an expect command?:

expect -c 'spawn ssh root@your-domain.com;expect password;send "your-password\n";interact

That command gives the password automatically.

查看更多
荒废的爱情
6楼-- · 2018-12-31 19:22
echo <password> | su -c <command> <user> 

This is working.

查看更多
冷夜・残月
7楼-- · 2018-12-31 19:25

For sudo there is a -S option for accepting the password from standard input. Here is the man entry:

    -S          The -S (stdin) option causes sudo to read the password from
                the standard input instead of the terminal device.

This will allow you to run a command like:

echo myPassword | sudo -S ls /tmp

As for ssh, I have made many attempts to automate/script it's usage with no success. There doesn't seem to be any build-in way to pass the password into the command without prompting. As others have mentioned, the "expect" utility seems like it is aimed at addressing this dilemma but ultimately, setting up the correct private-key authorization is the correct way to go when attempting to automate this.

查看更多
登录 后发表回答