暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Linux/Mac ssh 自动输入密码 - expect使用

digoal 2021-01-01
2385

作者

digoal

日期

2021-01-30

标签

PostgreSQL , ssh


背景

注意, 脚本中的注释实际使用时全部删掉, 保留到真正有用的部分即可, 因为expect无法解释注释, 会导致报错.

想搞一个使用ssh登录批量ip地址执行命令,自动输入密码的脚本,但是ssh不能使用标准输入来实现自动输入密码,于是了解到了expect这个可以交互的命令

是什么

查看使用man查看expect,是这么说的,使用谷歌翻译一下

Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue.
In addition, the user can take control and interact directly when desired, afterward returning control to the script.

我是这么理解的,expect是一个程序,更准确来讲是一个解释型语言,用来做交互的

命令

常用命令

spawn:开启一个进程,后面跟命令或者程序(需要做交互的,比如ssh) expect:匹配进程中的字符串 exp_continue:多次匹配时用到 send:当匹配到字符串时发送指定的字符串信息 set:定义变量 puts:输出变量 set timeout:设置超时时间 interact:允许交互 expect eof:

简单用法

ssh登录ip,自动输入密码, vim ~/sshlogin

```

!/usr/bin/expect #使用expect解释器

spawn ssh -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 root@192.168.56.101 #开启一个进程ssh
expect {
"yes/no" { send "yes\r"; exp_continue } #当匹配到"yes/no时,就是需要你输入yes or no时,发送yes字符串,\r带表回车;exp_continue继续匹配
"password:" { send "sanshen6677\r" } #当匹配到password,就是该输入密码,发送密码,并\r回车。注意{之前要有空格。
}
interact #允许交互,这样你就会留在登录之后的窗口,进行操作,没有interact程序执行完成后就跳回当前用户ip。
```

脚本使用方法

chmod +x sshlogin #添加权限直接执行 ./sshlogin

或者

expect sshlogin #使用expect解释器执行

一般情况下用户名,ip,密码是需要作为参数传进去的,因为和bash不一样,所以使用$1接收是错误的。

```

!/usr/bin/expect

set user [lindex $argv 0] #定义变量,接收从0开始,bash是从1开始
set ip [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$ip
expect {
"yes/no" {send "yes\r"; exp_continue}
"password" {send "$password\r"}
}
interact
```

执行一下

./sshlogin root 192.168.56.101 password123

ssh执行命令,需要在尾部加expect eof

```

!/usr/bin/expect

set user [lindex $argv 0]
set ip [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$ip "df -Th" #执行一条命令
expect {
"yes/no" {send "yes\r"; exp_continue}
"password" {send "$password\r"}
}
expect eof
```

也可以使用bash,内部调用expect

```

!/usr/bin/bash 使用#bash解释器

user=$1
ip=$2
password=$3
expect << EOF

spawn ssh $user@$ip "df -Th"
expect {
"yes/no" {send "yes\r"; exp_continue}
"password" {send "$password\r"}
}
expect eof

EOF
```

bash sshlogin root 192.168.56.101 sanshen6677 #使用bash执行

PostgreSQL 许愿链接

您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.

9.9元购买3个月阿里云RDS PostgreSQL实例

PostgreSQL 解决方案集合

德哥 / digoal's github - 公益是一辈子的事.

digoal's wechat

文章转载自digoal,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论