jekins远程连接服务器,自动输入密码命令

235 阅读2分钟

文章目录

应用

jekins机子没有配置ssh密钥,但是知道部署服务器的登录用户名,密码,不建议使用root用户;

实现目标

Linux ssh下执行ssh命令远程登录其他机器,总是需要输入密码,如果人工去登录,输入密码那还可以,但是让程序自动化登录远程ssh服务器,并执行命令着就比较麻烦了。
Linux下有个程序是expect,它可以模拟键盘,输入文本。

首先安装expect

经常看到一些脚本有会expect、spawn、send关键字,这几个关键字都是在expect程序里面使用的。

sudo apt-get install expect
yum install expect

远程使用密码

#!/usr/bin/expect
 
set timeout 5
 
password=ppp
 
spawn ssh user@localhost -p 22
expect {
     "(yes/no)" { send "yes\r" ; exp_continue }
     "password:" { send "$password\r" }
}
expect user@*   {send \" ls -l \r\" }  ;
expect user@*  { send exit \r } ;
expect 100% ;
expect eof ;
  • 注意第一行使用的是#!/usr/bin/expect而不是普通的bash脚本那样
  • expect都是使用{},且{、}使用时,前后需要留空格
  • 例子使用花括号,表示使用一组并列表达式,只要其中一项符合,就会执行该项,类似switch

expect运行shell脚本

expect -c "
            set timeout 1;
            spawn ssh user@localhost -p 22  ;
            expect {
                yes /no { send \" yes \r\"; exp_continue }
                *assword* { send \"password\r\" }
            } ;
            expect user@*   {send \" ls -l \r\" }  ;
            expect user@*  { send exit \r } ;
            expect eof ;
        "
  • expect的参数-c后面是字符串,里面就相当于脚本里面的内容了。
  • 用;分号隔开,可以在同一行里。
  • 里面的"引号,使用"来代替。
  • 第9行的exit最好要有。退出ssh,这样程序不会阻塞。我如果没有使用,在这个shell命令执行完,无法立刻输入字符。
  • expect脚本必须以interact或expect eof结束,执行自动化任务通常expect eof就够了

expect与scp

expect -c "
            set timeout 1;
            spawn scp -P 22 user@remoteHost: /tmp/file .txt ~/  ;
            expect {
                yes /no { send \" yes \r\"; exp_continue }
                *assword* { send \"password\r\" }
            } ;
            expect user@*   {send \" ls -l \r\" }  ;
            expect user@*  { send exit \r } ;
            expect 100% ;
            expect eof ;
        "

也可以使用sshpass,我没用,jekins服务器没有安装,也连不上;