1. 程式人生 > >linux shell ssh實現自動登入,並且執行一些操作並返回到當前主機

linux shell ssh實現自動登入,並且執行一些操作並返回到當前主機

#!/usr/bin/expect -f
#-------------------------------------------------- about us
# product: monitorone
# Author:matthew
# Last Modified: xxx
# version:xxx
# user:this script will help you to monitor many linux(unix) machine
# license: this script is based GPL
set loginuser "user" 
set loginpass {password}


set ipaddr [lrange $argv 0 0] 
set timeout 300
set cmd_prompt "]#|~]?"


#-------------------------------------------------- login by ssh 
spawn ssh
[email protected]
$ipaddr
set timeout 300
expect {
-re "Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
} -re "assword:" {
send "${loginpass}\r"
} -re "Permission denied, please try again." {
exit
} -re "Connection refused" {
exit
} timeout {
exit
} eof {
exit
}
}


expect {
-re "assword:" {
send "$loginpass\r"
}
-re $cmd_prompt {
send "\r"
}
}


#---------------------------------------------------- now,we do some commands
#exec sleep 1
expect {
-re $cmd_prompt {
send "sudo su -\r"
send "touch /opt/2222222222222.c\r"
}
}


exit
interact