命令记不住

登陆

Ops 方式实现自动输入密码远程登录

Ops方式实现自动输入密码远程登录

1.需求

使用ssh和scp避免出现终端交互,在脚本中设置密码。

例如:ssh和scp

2.环境准备

Linux环境:

yum install expect 

Mac环境:

brew install expect 

3.处理交互环境

第一行:#!/usr/bin/expect

设置密码:set passwd your_passwd

超时时间:set timeout 20

ssh示例:

#!/usr/bin/expect
spawn ssh [email protected] -p5213
expect "*password:"
send "Passw0rd\r"
expect "*#"
interact

执行:

$./proxy_centos.sh
spawn ssh [email protected] -p5213
[email protected]'s password:
Last login: Tue Oct 12 10:45:36 2021 from 222.130.26.242

Welcome to Alibaba Cloud Elastic Compute Service !

[root@alicloud ~]#

scp示例:

#!/usr/bin/expect

set timeout 20
if { [llength $argv] < 2} {
    puts "Usage:"
    puts "$argv0 local_file remote_path"
    exit 1
}

set remote_path [lindex $argv 1]
set passwd your_passwd
set passwderror 0

spawn scp -P5213 $local_file $remote_path

expect {
    "*assword:*" {
        if { $passwderror == 1 } {
        puts "passwd is error"
        exit 2
        }
        set timeout 1000
        set passwderror 1
        send "$passwd\r"
        exp_continue
    }
    "*es/no)?*" {
        send "yes\r"
        exp_continue
                }
    timeout {
        puts "connect is timeout"
        exit 3
    }
}

执行:

./scp_localfile_remote.sh ./local_file [email protected]:/tmp

1

4.自动输入yes

脚本可以继续优化

#!/bin/bash

for i in `cat needye.list`
do
/usr/bin/expect <<-EOF
spawn ssh $i
expect {
"yes/no" { send "yes\r" }
}
expect "*$"
send "exit\r"
EOF
done
推荐阅读