expect免输密码登录服务器

1. 首选是往authorized_keys里追加公钥来实现

2. 第二种选择是使用expect来自动填充密码

3. 第三种是使用echo打印密码,然后自动手动复制粘贴

## 二、使用expect来自动填充密码

1)安装expect

sudo apt install expect # Ubuntu/Debian

sudo yum install expect # Centos/RedHat

2)创建.exp文件:vi .ssh_server.exp

#!/usr/bin/expect -f
set user  [ lindex $argv 0  ]
set host  [ lindex $argv 1  ]
set passwd [ lindex $argv 2  ]
set project [ lindex $argv 3  ]
set port [ lindex $argv 4  ]
spawn ssh -p $port $user@$host
expect {
    "yes/no" { send "yes\r"; exp_continue}
    "password:" { send "$passwd\r" }
}

expect "$ "
send "cd coding/$project \r"
interact

3)添加可执行权限:chmod +x .ssh_server.exp

4)创建另一个.exp文件:vi .scp_to_server.exp

#!/usr/bin/expect -f
set user  [ lindex $argv 0  ]
set host  [ lindex $argv 1  ]
set passwd [ lindex $argv 2  ]
set file_or_folder [ lindex $argv 3  ]
set port [ lindex $argv 4  ]

spawn scp -r -P $port $file_or_folder $user@$host:~
expect {
    "yes/no" { send "yes\r"; exp_continue}
    "password:" { send "$passwd\r" }
}

expect EOF

5) 添加可执行权限:chmod +x .scp_to_server.exp

6)创建scp+ssh多功能脚本:vi to_my_server.sh

#!/usr/bin/bash

user="username"
host="ip-or-domain"
passwd="password"
project="my-project"
port=22

if [ $1 ] then;
    ./.scp_to_server.exp $user $host $passwd $1 $port
else
    ./.ssh_server.exp $user $host $passwd $project $port
fi

7)添加可执行权限:chmod +x to_my_server.sh

## 后记@2023-12-06

脚本整合进了github中公开的carstino库:git clone git@github.com:waketzheng/carstino.git

克隆到本地后,修改里面的to_my_server.sh脚本,就可以一键ssh和scp了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值