python-paramiko通过远程操作linux

1. python-paramiko通过远程操作linux

  • python3 远程操作linux

    • 使用第三方paramiko库,对于实现运维自动部署很重要

      pip3 install  paramiko
      
    • 引用的cryptography输出有问题

      pip install cryptography
      
  • 案例1:通过paramiko使用用户密码远程操作linux

    • 使用python编写,通过paramiko使用用户密码远程操作linux

      #!/usr/bin/env python
      # _*_ coding: utf-8 _*_
      # Author:shichao
      # File: .py
      
      
      import paramiko
      
      # 远程连接 ip和端口
      transport = paramiko.Transport( '192.168.0.200', 22 )
      
      # 连接私钥
      # pkey = paramiko.RSAKey.from_private_key_file( '/root/.ssh/id_rsa' )
      
      # 连接密码
      pwd = '123456'
      
      # 连接用户和密码
      transport.connect( username = 'root', password = pwd )
      # 通过paramiko ssh连接
      ssh = paramiko.SSHClient()
      ssh._transport = transport
      
      # stdio 是输入, stdout 是输出,stderr错误输出
      stdio, stdout, stderr = ssh.exec_command( "ifconfig eth0 | awk 'NR==2 {print $2}'" )
      channel = stdout.channel
      status = channel.recv_exit_status()
      
      # stdout标准输出读取数据
      stdout = stdout.read().decode()
      
      # stderr标准错误数据输出读取数据
      stderr = stderr.read().decode()
      
      
      ssh.close()
      transport.close()
      
      print( stdout )
      
      
      
      if status >= 1:
          print(stderr)
      else:
          print("执行成功")
      
    • 执行结果

      # python3 test_paramiko.py
      192.168.0.200
      
  • 案例2:通过paramiko通过密钥远程操作linux

    • 本机安装服务器密钥

      [admin@shichaodeMacBook-Pro ~]# ssh-keygen -t rsa
      Generating public/private rsa key pair.
      Enter file in which to save the key (/Users/admin/.ssh/id_rsa): 
      Enter passphrase (empty for no passphrase): 
      Enter same passphrase again: 
      Your identification has been saved in /Users/admin/.ssh/id_rsa
      Your public key has been saved in /Users/admin/.ssh/id_rsa.pub
      The key fingerprint is:
      SHA256:pU9abOwMKntMChDm70ffna5DCRy2n83c9I71aE7Sb+0 [email protected]
      The key's randomart image is:
      +---[RSA 3072]----+
      |                 |
      |..     o         |
      |o.    o o .      |
      |..     + =   .   |
      | ..     S % o .  |
      |  .. ... # + o o |
      |  ..o+o + = o *.o|
      |   ..+o. o o +oo+|
      |    o.   .+. o.oE|
      +----[SHA256]-----+
      [admin@shichaodeMacBook-Pro ~]# cd .ssh 
      [admin@shichaodeMacBook-Pro .ssh]# ll
      total 32
      drwx------   6 admin  staff   192 Jun 30 11:01 ./
      drwxr-xr-x+ 60 admin  staff  1920 Jun 30 10:59 ../
      -rw-------   1 admin  staff  2622 Jun 30 11:01 id_rsa
      -rw-r--r--   1 admin  staff   586 Jun 30 11:01 id_rsa.pub
      -rw-------   1 admin  staff  3616 Jun 10 13:59 known_hosts
      -rw-------   1 admin  staff  2950 May 10 16:50 known_hosts.old
      
    • 拷贝公钥到服务器端

      [admin@shichaodeMacBook-Pro .ssh]# ssh-copy-id [email protected]
      /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/admin/.ssh/id_rsa.pub"
      The authenticity of host '192.168.0.200 (192.168.0.200)' can't be established.
      ED25519 key fingerprint is SHA256:s/wgZLKfYoMCzTXN3RNfjSlFi6a68iT0wQDkh1CUUQg.
      This key is not known by any other names
      Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
      /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
      /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
      [email protected]'s password: 
      
      Number of key(s) added:        1
      
      Now try logging into the machine, with:   "ssh '[email protected]'"
      and check to make sure that only the key(s) you wanted were added.
      
      
    • 使用key免密钥连接测试

      [admin@shichaodeMacBook-Pro .ssh]# ssh [email protected]
      Last login: Thu Jun 30 09:58:32 2022 from 192.168.0.160
      [root@ansible ~]# ifconfig 
      docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
              inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
              ether 02:42:35:bb:34:55  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
      
      eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
              inet 192.168.0.200  netmask 255.255.255.0  broadcast 192.168.0.255
              inet6 fe80::20c:29ff:fe84:914d  prefixlen 64  scopeid 0x20<link>
              ether 00:0c:29:84:91:4d  txqueuelen 1000  (Ethernet)
              RX packets 441188  bytes 281747902 (268.6 MiB)
              RX errors 0  dropped 37  overruns 0  frame 0
              TX packets 243722  bytes 118421451 (112.9 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 1000  (Local Loopback)
              RX packets 3  bytes 208 (208.0 B)
              RX errors 0  dropped 0  overruns 0  frame 0
              TX packets 3  bytes 208 (208.0 B)
              TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
      
    • 使用python编写,通过paramiko使用免密钥的方式操作linux

      #!/usr/bin/env python
      # _*_ coding: utf-8 _*_
      # Author:shichao
      # File: .py
      
      
      import paramiko
      import  time
      
      # 远程连接 ip和端口
      transport = paramiko.Transport( '192.168.0.200', 22 )
      
      # 连接私钥
      pkey = paramiko.RSAKey.from_private_key_file( '/Users/admin/.ssh/id_rsa' )
      
      # 连接用户和密码
      transport.connect( username = 'root', pkey = pkey )
      # 通过paramiko ssh连接
      ssh = paramiko.SSHClient()
      ssh._transport = transport
      
      # stdio 是输入, stdout 是输出,stderr错误输出
      stdio, stdout, stderr = ssh.exec_command( "ifconfig eth0 | awk 'NR==2 {print $2}'" )
      time.sleep(2)
      channel = stdout.channel
      status = channel.recv_exit_status()
      
      # stdout标准输出读取数据
      stdout = stdout.read().decode()
      
      # stderr标准错误数据输出读取数据
      stderr = stderr.read().decode()
      
      
      ssh.close()
      transport.close()
      
      
      
      
      
      if status >= 1:
          print(stderr)
      else:
          print(stdout)
      
    • 运行脚本,查看结果

      # python3 test_paramiko.py
      192.168.0.200
      
01-31 10:58