Linux中自动输入密码等操作之expect并给expect传参

您所在的位置:网站首页 ssh无法输入密码怎么办 Linux中自动输入密码等操作之expect并给expect传参

Linux中自动输入密码等操作之expect并给expect传参

2024-07-13 20:25| 来源: 网络整理| 查看: 265

在写脚本的时候,我们往往需要在大量的机器中登入机器或者scp或者rsync进行拷贝文件等操作,这时就用到了expect这个脚本工具了。

下面是一个登录远程机器的代码:

a.sh:

#!/usr/bin/expect spawn ssh [email protected] "bash /data/soft/shell/hello.sh" expect "connecting (yes/no)?" send "yes\n" expect "password:" send "root\r" interact

另一种写法(这种写法可以选择其中一种发送):

#!/usr/bin/expect spawn ssh [email protected] expect { "yes/no" {send "yes\r";exp_continue} "password" {send "root\n"} } interact #interact会进入交互的界面 #!/usr/bin/expect spawn ssh [email protected] expect { "connecting (yes/no)?" {send "yes\r";exp_continue} "password:" {send "root\n"} } expect eof #立即退出

 

bash还可以调用这个a.sh,

下面是一个bash的脚本文件,调用a.sh:

test.sh:

#!/bin/bash expect if [ $? -ne 0 ];then echo "准备安装expect......" yum install -y expect fi mv ~/.ssh ~/.ssh.bak expect ./a.sh mv ~/.ssh.bak ~/.ssh

mv ~/.ssh ~/.ssh.bak是为了a.sh里两个expect做准备的,因为ssh一旦输入了yes,会在.ssh目录下的known_hosts文件中做记录,就不会出现“connecting (yes/no)?”这样的选择了,然后程序就会报错,这个是个解决的方案。

针对于expect这个程序使用rpm安装即可,当然也可以用yum安装,但是在没网的情况下只能用rpm或者二进制安装。

这里使用rpm安装:

如何解决rpm安装包依赖问题_wtl1992的博客-CSDN博客需求背景你需要安装几个rpm包,当时当你执行rpm -ivh *.rpm的时候,却提示需要一大堆依赖。你被不允许配置yum源,你也不能一个一个去尝试包和包之间的依赖关系。解决方法先在通互联网的机器上配置互联网yum源再安装#yum -y install yum-util* 工具缓存你需要安装的rpm,但是不安装,使用yum主要是自动解决依赖关系,把相关的依赖包一网打尽。使用命令:mkdir -p /YOUR/DOWNLOAD/PATHyum install &lhttps://blog.csdn.net/wtl1992/article/details/122256926?spm=1001.2014.3001.5501

给expect传参 : #!/usr/bin/expect set timeout 10 set username [lindex $argv 0] set password [lindex $argv 1] set hostname [lindex $argv 2] spawn ssh-copy-id -i .ssh/id_rsa.pub $username@$hostname expect "yes/no" send "yes\r" expect "password:" send "$password\r" expect eof



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3