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

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值