PYTHON通过密钥SSH远程登陆服务器并执行命令

系统环境:CENTOS7

先做好SSH密钥登陆的配置,简单一些说就是将A机器的/root/.ssh/id_rsa.pub的内容追加到B机器的/root/.ssh/authorized_keys当中

从而以root用户的资格在A机器实现对B机器的密钥认证登陆

python的脚本如下:

[root@V71 python]# cat 5s.py 
#!/usr/bin/python
# -*- coding:utf-8 -*-
 
import paramiko
import sys
 
def sshexeccmd(ip,cmd):
    try:
        
        ssh = paramiko.SSHClient()
        #add to host_allow
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        # pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='yourpassword')
        pkey = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
        
        ssh.connect(hostname=ip,
                    port=22,
                    username='root',
                    pkey=pkey)
        
        
        stdin, stdout, stderr = ssh.exec_command("ifconfig")
        
        print(stdout.read())
        print(stderr.read())
        
        ssh.close()
    except Exception,e:
        print e
 
if __name__ =='__main__':
    if len(sys.argv) != 3:
        print 'python pyfile ip cmd'
        sys.exit()
    print 'Host: %s' % sys.argv[1]
    print 'Cmd: %s' % sys.argv[2]
    sshexeccmd(sys.argv[1],sys.argv[2])
    print '$' * 100

执行效果:

[root@V71 python]# python 5s.py 192.168.156.72 ifconfig
Host: 192.168.156.72
Cmd: ifconfig
eno16777736: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.156.72  netmask 255.255.255.0  broadcast 192.168.156.255
        inet6 fe80::20c:29ff:fe40:7a2f  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:40:7a:2f  txqueuelen 1000  (Ethernet)
        RX packets 86458  bytes 68290823 (65.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 69211  bytes 19138737 (18.2 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 0  (Local Loopback)
        RX packets 4  bytes 420 (420.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 4  bytes 420 (420.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

扫描二维码关注公众号,回复: 4026073 查看本文章

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:87:fc:af  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

猜你喜欢

转载自blog.csdn.net/lsysafe/article/details/82981932