Linux下免交互模式的远程管理实现
通过linux脚本及expect可以不交互进行linux服务器的批量管理。
一、远程传输文件
cat send_file.sh
#!/usr/local/bin/expect -f
## 输入两个参数
set file [lindex $argv 0 ]
set ip [lindex $argv 1 ]
##设置密码
set password yyyyyy
##设置超时时间
set timeout 10
##执行文件传输命令
spawn scp $file root@$ip
##可能遇到两种情况需要进行交互
expect {
"*yes/no" { send "yes\r"; exp_continue }
"password:" { send "$password\r" }
}
##结束交互
expect eof
命令运行示例:./send_file.sh filename.tar 10.100.100.100:/root
二、远程操作linux命令
cat os_cmd.sh
#!/usr/local/bin/expect -f
set ip [lindex $argv 0 ]
set password yyyyyy
set timeout 10
##执行ssh远程操作命令
spawn ssh root@$ip
expect {
"*yes/no" { send "yes\r"; exp_continue }
"password:" { send "$password\r" }
}
expect "#*"
## 执行远程linux上命令
send "cd /xxxx/scripts/\r"
send "\\cp /root/filename.tar ./\r"
send "tar xvf filename.tar\r"
send "exit\r"
expect eof
命令运行示例:./os_cmd.sh 10.100.100.100
附:ssh可以通过如下一条命令直接进行操作,如 ssh 10.100.100.100 'cd /xxxx/scripts;cp /root/filename.tar ./;tar xvf filename.tar'