在shell中使用expect+ssh登陆远程服务器

登录流程:本地A 先登录到 B

#!/usr/bin/expect -f
set timeout 30
spawn ssh B_user@B_IP -l B_user -p 22           #ssh命令登录
expect "*password:" { send "B_user_passwd\r" }  #自动输入密码B_user_passwd
expect "$*" { send "pwd\r" }                    #登录成功后执行pwd
interact

---------------------

1.安装expect工具:
ubuntu:apt-get install expect
rhel: yum install expect
2.在shell脚本中使用expect,vi exp.sh:
#!/usr/bin/expect -f
set timeout 30                 #设置连接超时时长
spawn ssh root@ip_address      #登陆服务器用户和地址
expect "*password:*"           #等到输入密码时
#下面这条命令是输入root用户密码,注意后面的\r(回车符号)一定要加,用\n也行
send "huang\r"
expect "*#"                    #等待上一条命令执行完成
send  "cd /home\r"             # 进入/home目录
expect "*#"
send "touch test\n"            #创建文件test
expect "*#"
send "echo 'hello' > test\r"   #向test文件中添加字符串hello
expect "*#"                  
send "tar -cvf test.tar test\r"  
expect "*#"
send "
touch hello\r                     
"
#上面红色字体命令,创建hello文件,这一条命令用了3行,你没有看错,确实可以这样写
expect "*#"
send "cat > hello << EOF         #向hello文件中添加下面3行文字
hello
world 
my dod
EOF\r"
expect "*#"
exit
#expect eof



猜你喜欢

转载自blog.csdn.net/jdbc/article/details/79936480