欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

ssh自动登录的4种实现方法

程序员文章站 2023-11-15 15:46:46
1. 自动ssh/scp方法 a为本地主机(即用于控制其他主机的机器) ;b为远程主机(即被控制的机器server), 假如ip为192.168.60.110;a和b的系...

1. 自动ssh/scp方法

a为本地主机(即用于控制其他主机的机器) ;
b为远程主机(即被控制的机器server), 假如ip为192.168.60.110;
a和b的系统都是linux

在a上运行命令:
# ssh-keygen -t rsa (连续三次回车,即在本地生成了公钥和私钥,不设置密码)
# ssh root@192.168.60.110 "mkdir .ssh" (需要输入密码)
# scp ~/.ssh/id_rsa.pub root@192.168.60.110:.ssh/id_rsa.pub (需要输入密码)

在b上的命令:
# touch /root/.ssh/authorized_keys (如果已经存在这个文件, 跳过这条)
# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys (将id_rsa.pub的内容追加到authorized_keys 中)

回到a机器:
# ssh root@192.168.60.110 (不需要密码, 登录成功)

2. 控制n个机器如上所述自动登录

那就需要n对钥匙(密钥和公钥), ssh-keygen 命令可以随意更改钥匙对的名字, 比如:
# ssh-keygen -t rsa
generating public/private rsa key pair.
enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_192.168.60.110

这样私钥和公钥的名字分别就是: id_rsa_192.168.60.110和 id_rsa_192.168.60.110.pub;然后将 id_rsa_192.168.60.110.pub 文件的内容, 追加到sever的 ~/.ssh/authorized_keys文件中,最后, 在本地用ssh命令的 -i 参数指定本地密钥, 并登录:
# ssh -i /root/.ssh/id_rsa_192.168.60.110 someone@192.168.60.110

scp也是一样的
# scp -i /root/.ssh/id_rsa_192.168.60.110 filename someone@192.168.60.110:/home/someone

在文件.bashrc中加下两行,每次做同样的操作就不用敲入这样长的命令了:
alias sshcell='ssh -i /root/.ssh/id_rsa_192.168.60.110 someone@192.168.60.110'
alias scpcell='scp -i /root/.ssh/id_rsa_192.168.60.110 filename someone@192.168.60.110:/home/someone'

这样,直接键入一下指令实现ssh和scp自动登录:
# sshcell
# scpcell

3. 自动ssh/scp脚本

如果需要从a,到b,然后才能够到c,那么需要ssh和scp两次,是比较麻烦的。
ssh自动登录:
#!/usr/bin/expect -f
set timeout 30
spawn ssh weiqiong@b
expect "password:"
send "ppppppr"
expect "]*"
send "ssh weiqiong@cr"
expect "password:"
send "ppppppr"
interact

scp从a拷贝文件到c:
#!/usr/bin/expect -f
set timeout 300
set file [lindex $argv 0]
spawn scp $file weiqiong@b:/home/weiqiong
expect "password:"
send "ppppppr"
expect "]*"
spawn ssh weiqiong@b
expect "password:"
send "ppppppr"
expect "]*"
send "scp $file weiqiong@c:/home/weiqiongr"
expect "password:"
send "ppppppr"
expect "]*"
exit
interact

scp从c拷贝文件到a:
#!/usr/bin/expect -f
set timeout 300
set file [lindex $argv 0]
spawn ssh weiqiong@b
expect "password:"
send "ppppppr"
expect "]*"
send "scp weiqiong@c:/home/weiqiong/$file .r"
expect "password:"
send "ppppppr"
expect "]*"
send "exitr"
expect "]*"
spawn scp weiqiong@b:/home/weiqiong/$file .
expect "password:"
send "ppppppr"
interact

4. 建立ssh/scp通道

比如说我的机器是a,中间服务器为b,目标服务器是c
从a可以ssh到b,从b可以ssh到c,但是a不能直接ssh到c
现在展示利用ssh通道技术从a直接传输文件到c

1. ssh -l1234:c:22 userid@b
input b's password
(1234是本机a的空闲端口,该指令需要a机器上的root用户权限,实际上是在本机1234端口建立了一个通道)

2. 打开一个新的console,键入:
scp -p1234 filename userid@localhost:
input c's password