当前位置:   article > 正文

python paramiko

python paramiko

Paramiko

一、安装,下载

  1、下载安装 pycrypto-2.6.1.tar.gz  (apt-get install python-dev)

    解压,进入,python setup.py build【编译】,python setup.py install 【安装】  ----》import Crypto

  2、下载安装 paramiko-1.10.1.tar.gz  

    解压,进入,python setup.py build【编译】,python setup.py install 【安装】---》  import paramiko

二、paramiko 功能

1、连接远程服务器,并执行操作

用户名和密码连接

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. import paramiko
  4. ssh = paramiko.SSHClient()
  5. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  6. ssh.connect('192.168.1.108', 22, 'alex', '123')
  7. stdin, stdout, stderr = ssh.exec_command('df')
  8. print stdout.read()
  9. ssh.close();

2、上传和下载文件

  1. import os,sys
  2. import paramiko
  3. t = paramiko.Transport(('182.92.219.86',22))
  4. t.connect(username='wupeiqi',password='WOshiniba8')
  5. sftp = paramiko.SFTPClient.from_transport(t)
  6. sftp.put('/tmp/test.py','/tmp/test.py')
  7. t.close()
  8. import os,sys
  9. import paramiko
  10. t = paramiko.Transport(('182.92.219.86',22))
  11. t.connect(username='wupeiqi',password='WOshiniba8')
  12. sftp = paramiko.SFTPClient.from_transport(t)
  13. sftp.get('/tmp/test.py','/tmp/test2.py')
  14. t.close()

3.通过SSH连接

  ssh-keygen -t rsa

  ssh-copy-id -i ~/ssh/id_rsa.pub wupeiqi@192.168.159.129

  1. import paramiko
  2. private_key_path = '/home/auto/.ssh/id_rsa'
  3. key = paramiko.RSAKey.from_private_key_file(private_key_path)
  4. ssh = paramiko.SSHClient()
  5. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  6. ssh.connect('182.92.219.96 ', 22, 'wupeiqi', 'xxxx', key)
  7. stdin, stdout, stderr = ssh.exec_command('df')
  8. print stdout.read()
  9. ssh.close();

5.上传和下载文件

  1. import paramiko
  2. pravie_key_path = '/home/auto/.ssh/id_rsa'
  3. key = paramiko.RSAKey.from_private_key_file(pravie_key_path)
  4. t = paramiko.Transport(('182.92.219.86',22))
  5. t.connect(username='wupeiqi',pkey=key)
  6. sftp = paramiko.SFTPClient.from_transport(t)
  7. sftp.put('/tmp/test3.py','/tmp/test3.py')
  8. t.close()
  9. import paramiko
  10. pravie_key_path = '/home/auto/.ssh/id_rsa'
  11. key = paramiko.RSAKey.from_private_key_file(pravie_key_path)
  12. t = paramiko.Transport(('182.92.219.86',22))
  13. t.connect(username='wupeiqi',pkey=key)
  14. sftp = paramiko.SFTPClient.from_transport(t)
  15. sftp.get('/tmp/test3.py','/tmp/test4.py')
  16. t.close()

5、第三种连接

  1. import paramiko
  2. scp = paramiko.Transport(('182.92.219.86',22));
  3. scp.connect(username='wupeiqi',password='xxx');
  4. channel = scp.open_session();
  5. print channel.exec_command('mkdir hello')
  6. channel.close();
  7. scp.close();

6、交互式连接

  1. import paramiko
  2. import interactive
  3. ssh = paramiko.SSHClient()
  4. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  5. ssh.connect('192.168.1.108', 22, 'alex', '123')
  6. channel = ssh.invoke_shell()
  7. interactive.interactive_shell(channel)
  8. channel.close()
  9. ssh.close();

7、paramiko的demo.py文件

三、审计系统

需求:记录用户在服务器的所有操作!!

1、需要一台主机当作堡垒机

2、所有用户只能登录堡垒机

3、登录堡垒机后,可以对远程服务器进行操作

4、记录用户的所有操作

  【登录堡垒机】--> 【选择服务器】 --> 【操作服务器,并记录操作】

实现:

1、创建堡垒机用户

  adduser xxx

2、用户登录堡垒机后,自动执行脚本

  配置 .brashrc

  添加 /usr/bin/python /home/wupeiqi/share/workspace/07day07/section_two/menu.py

3、堡垒机提示与用户对应的服务器

  1. import os,sys
  2. msg = """
  3. \033[42;1mWelcome using old boy's auditing system!\033[0m
  4. """
  5. print msg
  6. host_dic = {
  7. 'zhangke': '10.0.0.137',
  8. 'xiaoqing': '10.0.0.135',
  9. 'hanxin' : '10.0.1.139'
  10. }
  11. while True:
  12. for hostname, ip in host_dic.items():
  13. print hostname,ip
  14. try:
  15. host = raw_input('Please choose one server to login:').strip()
  16. if host == 'quit':
  17. print "Goodbye!"
  18. break
  19. except KeyboardInterrupt:continue
  20. except EOFError:continue
  21. if len(host) ==0:continue
  22. if not host_dic.has_key(host) :
  23. print 'No host matched, try again.'
  24. continue
  25. print '\033[32;1mGoing to connect \033[0m', host_dic[host]
  26. os.system("python demo.py %s" % host_dic[host])

4、记录日志

  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distrubuted in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  18. import socket
  19. import sys
  20. # windows does not have termios...
  21. try:
  22. import termios
  23. import tty
  24. has_termios = True
  25. except ImportError:
  26. has_termios = False
  27. def interactive_shell(chan):
  28. if has_termios:
  29. posix_shell(chan)
  30. else:
  31. windows_shell(chan)
  32. def posix_shell(chan):
  33. import select
  34. oldtty = termios.tcgetattr(sys.stdin)
  35. try:
  36. tty.setraw(sys.stdin.fileno())
  37. tty.setcbreak(sys.stdin.fileno())
  38. chan.settimeout(0.0)
  39. f = file('/tmp/auto.log','a+')
  40. while True:
  41. r, w, e = select.select([chan, sys.stdin], [], [])
  42. if chan in r:
  43. try:
  44. x = chan.recv(1024)
  45. if len(x) == 0:
  46. print '\r\n*** EOF\r\n',
  47. break
  48. sys.stdout.write(x)
  49. sys.stdout.flush()
  50. except socket.timeout:
  51. pass
  52. if sys.stdin in r:
  53. x = sys.stdin.read(1)
  54. f.write(x)
  55. f.flush()
  56. if len(x) == 0:
  57. break
  58. chan.send(x)
  59. f.close()
  60. finally:
  61. termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
  62. # thanks to Mike Looijmans for this code
  63. def windows_shell(chan):
  64. import threading
  65. sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
  66. def writeall(sock):
  67. while True:
  68. data = sock.recv(256)
  69. if not data:
  70. sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
  71. sys.stdout.flush()
  72. break
  73. sys.stdout.write(data)
  74. sys.stdout.flush()
  75. writer = threading.Thread(target=writeall, args=(chan,))
  76. writer.start()
  77. try:
  78. while True:
  79. d = sys.stdin.read(1)
  80. if not d:
  81. break
  82. chan.send(d)
  83. except EOFError:
  84. # user hit ^Z or F6
  85. pass

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/603434
推荐阅读
相关标签
  

闽ICP备14008679号