shell脚本实现从A服务器连接B服务器——(shell应用)

一、密钥连接登录

详细介绍可参考:十章———远程访问及控制(应用——linux高级管理)

密钥连接登录步骤

[root@C7--01 ~]# ssh-keygen -t ecdsa                #生成root密钥
Generating public/private ecdsa key pair.
Enter file in which to save the key (/root/.ssh/id_ecdsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_ecdsa.
Your public key has been saved in /root/.ssh/id_ecdsa.pub.
The key fingerprint is:
SHA256:Rx4X1bEG7hyP5AZKCAG7rf/EmtTaAv/3GnrNXCdzljY root@C7--01
The key's randomart image is:
+---[ECDSA 256]---+
|   ..o.     .o.o.|
|    . . .   ... o|
|   .   . .o..+ o |
|    o   .o.o* =  |
|   . .  S.o  * ..|
|   .. o  .  .+ E |
|   .o. + .+ . B .|
|    oo* .o.+     |
|     =+=o.o.     |
+----[SHA256]-----+


[root@C7--01 .ssh]# scp /root/.ssh/id_ecdsa.pub [email protected]:/root   #上传到1.2机器上id_ecdsa.pub 文件
The authenticity of host '192.168.1.2 (192.168.1.2)' can't be established.
ECDSA key fingerprint is SHA256:iKbLEhg8UfqGICLymBBNoZqynedjXefz3LSjpQlcREg.
ECDSA key fingerprint is MD5:c9:5e:dc:c2:eb:b9:19:88:2e:6d:56:e9:ca:cf:33:4d.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.2' (ECDSA) to the list of known hosts.
[email protected]'s password: 
id_ecdsa.pub                                                                       100%  173    97.9KB/s   00:00    


      #在1.2机器上查看

[root@C7--02 ~]# ls
anaconda-ks.cfg  id_ecdsa.pub  yum.sh

[root@C7--02 ~]# mkdir -p /root/.ssh
[root@C7--02 ~]# cat id_ecdsa.pub >> /root/.ssh/authorized_keys



[root@C7--01 .ssh]# ssh 192.168.1.2          #验证可以没有密码连接
Last login: Tue Nov  2 03:27:45 2021 from 192.168.1.1

[root@C7--02 ~]# ip a
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:18:f4:54 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.2/24 brd 192.168.1.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::7627:d369:e086:2468/64 scope link 
       valid_lft forever preferred_lft forever

二、sshpass连接登录

在虚拟机中操作

1、安装sshpass工具

[root@C7--02 ~]# yum provides */sshpass        #在本地yum仓库查找sshpass软件包
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
aaa/filelists_db                                                                              | 3.1 MB  00:00:00     
No matches found

发现没有sshpass软件包

1.1、添加一个网卡(设置为桥接模式

shell脚本实现从A服务器连接B服务器——(shell应用)_第1张图片

 可以测试“ping”一下”百度“或者”京东“测试是否已经连接到互联网

 1.2、先在虚拟机上安装wget

[root@C7--01 ~]# yum  -y  install wget

1.3、在浏览器中搜索   mirrors.aliyun.com  网站 

shell脚本实现从A服务器连接B服务器——(shell应用)_第2张图片

shell脚本实现从A服务器连接B服务器——(shell应用)_第3张图片

 找到网络上的yum源

1.4、复制找到的yum源

[root@C7--01 ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
--2021-11-01 20:14:51--  https://mirrors.aliyun.com/repo/Centos-7.repo
正在解析主机 mirrors.aliyun.com (mirrors.aliyun.com)... 183.232.15.100, 120.237.196.241, 183.232.15.101, ...
正在连接 mirrors.aliyun.com (mirrors.aliyun.com)|183.232.15.100|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:2523 (2.5K) [application/octet-stream]
正在保存至: “/etc/yum.repos.d/CentOS-Base.repo”

100%[===========================================================================>] 2,523       --.-K/s 用时 0s      

2021-11-01 20:14:51 (1002 MB/s) - 已保存 “/etc/yum.repos.d/CentOS-Base.repo” [2523/2523])

1.5、安装

[root@C7--01 ~]# yum -y install sshpass   
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 sshpass.x86_64.0.1.06-2.el7 将被 安装         
...............
.....

2、创建文件保存用户信息

done[root@C7--01 ~]# vim usr_info

192.168.1.2 root 123.com


保存

编写sshpass脚本

[root@C7--01 ~]# vim ssh_02.sh

#!/bin/basd

ip=`awk '{print $1}' usr_info`
user=`awk '{print $2}' usr_info`
pass=`awk '{print $3}' usr_info`
command=$1
/usr/bin/sshpass -p $pass ssh -o StrictHostKeyChecking=no $user@$ip $command

 验证:

[root@C7--01 ~]# bash ssh_02.sh  ifconfig       
ens33: flags=4163  mtu 1500
        inet 192.168.1.2  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::7627:d369:e086:2468  prefixlen 64  scopeid 0x20
        ether 00:0c:29:18:f4:54  txqueuelen 1000  (Ethernet)
        RX packets 1153  bytes 117098 (114.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 827  bytes 96911 (94.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10
        loop  txqueuelen 1  (Local Loopback)
        RX packets 648  bytes 52368 (51.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 648  bytes 52368 (51.1 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

三、expect连接登录

1、安装expect软件包 

注意 /etc/yum.repos.d/CentOS-Base.repo 尽量剪切或删除到其他地方

[root@C7--01 ~]# yum -y install expect
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
正在解决依赖关系
--> 正在检查事务
---> 软件包 expect.x86_64.0.5.45-14.el7_1 将被 安装
--> 解决依赖关系完成

依赖关系解决

..........
....

2、先写一个expect的脚本

[root@C7--01 ~]# vim user.expect

#!/usr/bin/expect
set ip [lindex $argv 0]       #定义变量
set usr [lindex $argv 1]      #定义变量
set pass [lindex $argv 2]     #定义变量
set command [lindex $argv 3]  #定义变量

if { $argc != 4 } {
puts "错误:检查user.expect 文件 中的 ip usr pass command"
ecit 1
}

set timeout 30
spawn ssh $usr@$ip
expect {
       "(yes/no)" {send "yes\r"; exp_continue}
       "password:" {send "$pass\r"}
}
expect "$usr@*" {send "$command\r"}
expect "$usr@*" {send "exit\r"}
expect eof

3、写sshpass脚本

[root@C7--01 ~]# vim expect.sh

#!/bin/bash
ip=$(awk '{print $1}' usr_info)
usr=$(awk '{print $2}' usr_info)
pass=$(awk '{print $3}' usr_info)
command=$1
expect user.expect $ip $usr $pass $command

5、测试

[root@C7--01 ~]# bash expect.sh ifconfig
spawn ssh [email protected]
[email protected]'s password: 
Last login: Tue Nov  2 05:47:14 2021 from 192.168.1.1
[root@C7--02 ~]# ifconfig
ens33: flags=4163  mtu 1500
        inet 192.168.1.2  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::7627:d369:e086:2468  prefixlen 64  scopeid 0x20
        ether 00:0c:29:18:f4:54  txqueuelen 1000  (Ethernet)
        RX packets 1403  bytes 148606 (145.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1078  bytes 133681 (130.5 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10
        loop  txqueuelen 1  (Local Loopback)
        RX packets 715  bytes 57756 (56.4 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 715  bytes 57756 (56.4 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@C7--02 ~]# exit
登出
Connection to 192.168.1.2 closed.
spawn_id: spawn id exp6 not open
    while executing
"interact"
    (file "user.expect" line 22)

结论:不使用免登的情况下,可以使用sshpass进行免交互 或  expect进行免交互

expect中常用命令
spawn 交互程序开始后面跟命令或者指定程序 
expect 从进程中接收信息, 如果匹配成功, 就执行expect后的动作
send 向进程发送字符串
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
interact 允许用户交互
exit 退出expect脚本
eof expect执行结束, 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间

你可能感兴趣的:(服务器,运维)