1、使用expect
#!/usr/bin/expect
set host "192.168.1.10"
set username "nginx"
set password "nginx"
spawn rsync -av ~/test/ ${username}@${host}:~/test/
expect {
"(yes/no)?" { send "yes\r"; exp_continue}
"password:" { send "$password\r" }
}
expect eof
spawn scp -P "${port}" "${src}" ${username}@${host}:"${dst}"
expect {
"(yes/no)?" { send "yes\r"; exp_continue}
"password:" { send "$password\r" }
}
expect "100%"
expect eof
expect -c 直接在命令行中执行脚本中的命令
expect -c "
set timeout 30
spawn rsync -av ~/test/ ${username}@${host}:~/test/
expect {
"(yes/no)?" { send "yes\r"; exp_continue}
}
expect eof
"
2、使用加密传输
1)生成公钥
ssh-keygen -t rsa -C "nginx@192.168.1.19" -f ~/AUTH_NGINX
2)把公钥传给192.168.1.10,
scp AUTH_NGINX.pub nginx@192.168.1.10:~/.ssh
cat AUTH_NGINX.pub >> authorized_keys
3)传输文件
rsync -av -e "ssh -i AUTH_NGINX" test/ nginx@192.168.1.10:~/test/
3、免密码登录:
#!/usr/bin/expect
set host "xxxxxx"
set port "1101"
set username "root"
set password "xxxxxx"
spawn ssh -p ${port} ${username}@${host}
expect {
"(yes/no)?" { send "yes\r"; exp_continue}
"password:" { send "$password\r" }
}
#expect eof
expect "*#"
interact
expect传参数
#!/usr/bin/expect
#set host "${hostInterIp}"
#set port "${SSH_PORT}"
#set username "${SSH_USER}"
#set password "${SSH_PWD}"
set date [exec date "+%Y-%m-%d"]
set host [lindex $argv 0 ]
set username [lindex $argv 1]
set password [lindex $argv 2 ]
set port [lindex $argv 3 ]
spawn ssh -p ${port} ${username}@${host}
expect {
"(yes/no)?" { send "yes\r"; exp_continue}
"password:" { send "$password\r" }
}
#expect eof
expect "*#"
interact
4、用私钥去连接:
eval `ssh-agent`
ssh-add ~/.ssh/los 私钥