How do I use expect to connect via ssh to a system and change the password of the host system?

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I am automating the process of:
Connect to a system named "alpha" via ssh with password "alpha" for username "alpha". Once connected I would like to set the root password (to "kickass"). The system I am connecting to doesn't have a root password by default. I wrote this expect script to do the job but it doesn't work consistently. It works once and then if I change the password to test again, it waits at the "Enter new UNIX password:" prompt after issuing "sudo passwd root". Any ideas?

#!/usr/bin/expect -f set arg1 [lindex $argv 0] set force_conservative 1  ;# set to 1 to force conservative mode even if               ;# script wasn't run conservatively originally if {$force_conservative} {     set send_slow {1 .1}     proc send {ignore arg} {         sleep .1         exp_send -s -- $arg     } }  set timeout -1 spawn ssh alpha@$arg1 match_max 100000 expect -exact "password: " send -- "alpha\r" expect -exact "alpha@alpha:~\$ " send -- "sudo passwd root\r" expect -exact "password for alpha: " send -- "alpha\r" expect -exact "new UNIX password: " send -- "kickass\r" expect -exact "Retype new UNIX password: " send -- "kickass\r" expect -exact "alpha@alpha:~\$ " send -- "exit\r" expect eof 

Thanks.

回答1:

Expanding on Andrei Sfrent's comment:

Sudo normally has some kind of time-out value, so that if you issue a second sudo command within the time-out period you will not be asked for your password again. You could modify the code to something like this:

send -- "sudo passwd root\r" expect {         -exact "password for alpha: "             {                 send -- "alpha\r"                 exp_continue             }          -exact "new UNIX password: "             {                 send -- "kickass\r"             }         } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!