关键词搜索

源码搜索 ×
×

Python实用工具,paramiko模块,Python实现简易版SSH登录工具

发布2021-08-06浏览500次

详情内容

开发工具

Python版本: 3.5.4

相关模块:

paramiko模块以及一些Python自带的模块。

操作系统:Windows系列。

在这里插入图片描述

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

主要思路

目的:

制作命令行版的SSH登录工具。

需要实现的功能:
(1)添加/删除连接服务器需要的IP、端口、密码;
(2)自动输入密码登录远程服务器。

相关代码

auto_ssh.py

  1. # 自动登录远程服务器
  2. import os
  3. import base64
  4. import sys
  5. import paramiko
  6. path = os.path.dirname(os.path.abspath(sys.argv[0]))
  7. def ssh_connect(host_ip, host_port, username, password):
  8. ssh = paramiko.SSHClient()
  9. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  10. try:
  11. ssh.connect(host_ip, host_port, username, password, allow_agent=False, look_for_keys=False)
  12. print('[INFO]:Connect Successfully...')
  13. except:
  14. print('[INFO]:Fail to Connect...')
  15. while True:
  16. command = input('Enter the command(<#q> exit):')
  17. if command.strip() == '#q':
  18. ssh.close()
  19. return
  20. stdin, stdout, stderr = ssh.exec_command(command)
  21. out_content = stdout.readlines()
  22. if len(out_content) < 1:
  23. print('Error:')
  24. print(stderr.readlines())
  25. else:
  26. print('Result:')
  27. for o in out_content:
  28. print(o)
  29. def choose_host():
  30. f = open("{}/data/info.d".format(path))
  31. hosts = f.readlines()
  32. hosts_temp = []
  33. for h in hosts:
  34. if h.strip():
  35. hosts_temp.append(h)
  36. hosts = hosts_temp[:]
  37. hosts_len = len(hosts)
  38. if hosts_len <= 0:
  39. os.system('cls')
  40. print('[Warning]:No info saved before...')
  41. return
  42. while True:
  43. print('SSH......')
  44. print('FORMAT:\nAlias UserName@IP: PORT')
  45. for i in range(0, hosts_len):
  46. line_list = hosts[i].strip().split(' ')
  47. print("<{}>: {} |{}@{}: {}|".format(i+1, line_list[4], line_list[2], line_list[0], line_list[1]))
  48. choice = input('[SSH]:Choose the number or alias(<#q> exit):')
  49. is_alias = False
  50. is_num = False
  51. try:
  52. choice = int(choice)
  53. if choice < 1 or choice > hosts_len:
  54. os.system('cls')
  55. print('[Warning]:Number inexistence...')
  56. continue
  57. line_list = hosts[choice-1].split(' ')
  58. username = line_list[2]
  59. password = line_list[3]
  60. host_ip = line_list[0]
  61. host_port = line_list[1]
  62. is_num = True
  63. except:
  64. is_alias = True
  65. if is_alias:
  66. if choice.strip() == '#q':
  67. os.system('clear')
  68. return
  69. for h in hosts:
  70. if choice.strip() == h.split(' ')[4].strip():
  71. line_list = h.split(' ')
  72. username = line_list[2]
  73. password = line_list[3]
  74. host_ip = line_list[0]
  75. host_port = line_list[1]
  76. is_num = True
  77. if not is_num:
  78. os.system('cls')
  79. print('[Warning]:Alias inexistence...')
  80. continue
  81. # password = base64.decodestring(password)
  82. print('Start to connect {}@{}...'.format(username, host_ip))
  83. ssh_connect(host_ip, host_port, username, password)

settings.py

  1. # 信息保存/删除/输出
  2. import base64
  3. import os
  4. import sys
  5. import re
  6. import getpass
  7. path = os.path.dirname(os.path.abspath(sys.argv[0]))
  8. # 用于处理输入的数据格式
  9. def cmd_format(lable, rule):
  10. while True:
  11. print('{} (<#q> exit):'.format(lable))
  12. if lable.strip().strip(':').upper() == 'PASSWORD':
  13. temp = getpass.getpass()
  14. else:
  15. temp = input().strip()
  16. content = re.match(r'{}'.format(rule), temp)
  17. if content:
  18. break
  19. elif 'port' in lable:
  20. temp = 22
  21. break
  22. elif temp.strip() == '#q':
  23. os.system('cls')
  24. break
  25. os.system('cls')
  26. print('[Warning]: Invalid format...')
  27. return temp
  28. def about():
  29. f = open('{}/info/about.bat'.format(path))
  30. content = f.read()
  31. try:
  32. info = eval(content)
  33. os.system('cls')
  34. print('About SSH......')
  35. for k, v in info.items():
  36. print('{}: {}'.format(k, v))
  37. except:
  38. print('No Info......')
  39. f.close()
  40. return
  41. # 添加主机信息
  42. def add_host():
  43. print('Add host information......')
  44. print('[HELP]: INPUT <#q> exit...')
  45. # IP地址
  46. host_ip = cmd_format('Host IP:', '^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$')
  47. if host_ip == '#q':
  48. return True
  49. # 端口号
  50. host_port = cmd_format('Host port(Default 22):', '[0-9]+')
  51. if host_port == '#q':
  52. return True
  53. # 用户名
  54. username = cmd_format('User Name:', '^[^ ]+$')
  55. if username == '#q':
  56. return True
  57. # 密码
  58. password = cmd_format('Password:', '.*')
  59. if password == '#q':
  60. return True
  61. # password = base64.encodestring(password)
  62. # 输入别名
  63. alias = cmd_format('Local Alias:', '^[^ ]+$')
  64. if alias == '#q':
  65. return True
  66. elif not alias:
  67. os.system('cls')
  68. print('[Warning]: Alias cannot be empty...')
  69. return False
  70. # 查重
  71. f = open('{}/data/info.d'.format(path))
  72. hosts = f.readlines()
  73. for line in hosts:
  74. temp = line.strip('\n')
  75. if not temp:
  76. continue
  77. line_list = line.split(' ')
  78. if host_ip == line_list[0] and host_port == line_list[1]:
  79. os.system('cls')
  80. print('[Warning]: {}: {} existing...'.format(host_ip, host_port))
  81. return False
  82. if alias == line_list[4]:
  83. os.system('cls')
  84. print('[Warning]: Alias <{}> existing...'.format(alias))
  85. return False
  86. f.close()
  87. # 保存
  88. f = open('{}/data/info.d'.format(path), 'a')
  89. f.write('\n{} {} {} {} {}'.format(host_ip.strip('\n'), host_port, username.strip('\n'), password.strip('\n'), alias.strip('\n')))
  90. f.close()
  91. print('[INFO]:{} {}@{}:{} Add Successfully...'.format(alias.strip('\n'), username.strip('\n'), host_ip.strip('\n'), password.strip('\n')))
  92. return True
  93. def add_hosts():
  94. while True:
  95. if add_host():
  96. break
  97. print('\n\nTry Again:')
  98. # 删除主机信息
  99. def remove_host():
  100. while True:
  101. f = open('{}/data/info.d'.format(path))
  102. hosts = f.readlines()
  103. f.close()
  104. hosts_len = len(hosts)
  105. if hosts_len < 1:
  106. os.system('cls')
  107. print('[Warning]: No host info...')
  108. return
  109. print('Remove host information......')
  110. print('%' * 40)
  111. print('FORMAT:\nAlias UserName@IP: PORT')
  112. print('%' * 40)
  113. hosts_temp = []
  114. n = 1
  115. for i in range(0, hosts_len):
  116. if not hosts[i].strip():
  117. continue
  118. line_list = hosts[i].strip().split(' ')
  119. print("<{}>: {} |{}@{}: {}|".format(n, line_list[4], line_list[2], line_list[0], line_list[1]))
  120. n += 1
  121. hosts_temp.append(hosts[i])
  122. hosts = hosts_temp[:]
  123. choice = input('[Remove]: Choose the Number or Alias(<#q> to exit):')
  124. is_alias = False
  125. is_num = False
  126. try:
  127. choice = int(choice)
  128. if choice < 1 or choice > hosts_len:
  129. os.system('cls')
  130. print('[Warning]:Number inexistence...')
  131. continue
  132. del hosts[choice-1]
  133. is_num = True
  134. except:
  135. is_alias = True
  136. if is_alias:
  137. if choice.strip() == '#q':
  138. os.system('cls')
  139. break
  140. n = 0
  141. for h in hosts:
  142. if choice.strip() == h.split(' ')[4].strip():
  143. del hosts[n]
  144. is_num = True
  145. n += 1
  146. if not is_num:
  147. os.system('cls')
  148. print('[Warning]:Alias inexistence...')
  149. continue
  150. else:
  151. choice = input('Remove?[y/n]:')
  152. if choice.strip().upper() == 'Y':
  153. f = open("{}/data/info.d".format(path), "w")
  154. for h in hosts:
  155. f.write(h)
  156. print('Remove Successfully...')
  157. f.close()

SSH.py

  1. # 功能:
  2. # 添加/删除连接服务器需要的IP、端口、密码
  3. # 自动输入密码登录远程服务器
  4. # Python新手学习交流社区:594356095
  5. import os
  6. import sys
  7. import settings
  8. import auto_ssh
  9. path = os.path.dirname(os.path.abspath(sys.argv[0]))
  10. def main():
  11. while True:
  12. print('='*15 + 'SSH[Menu]' + '='*15)
  13. print('<1> Connect a host\n<2> Add host\n<3> Remove host\n<4> About\n[Help]: <q>:quit <clear>: clear screen')
  14. print('='*40)
  15. choice = input('Please select depend on tips:')
  16. if choice == 1 or choice == '1':
  17. auto_ssh.choose_host()
  18. elif choice == 2 or choice == '2':
  19. settings.add_hosts()
  20. elif choice == 3 or choice == '3':
  21. settings.remove_host()
  22. elif choice == 4 or choice == '4':
  23. settings.about()
  24. elif choice == 'q' or choice == 'Q' or choice == 'quit' or choice == 'exit':
  25. print('Bye...')
  26. sys.exit()
  27. elif choice == 'clear' or 'cls':
  28. os.system('cls')
  29. else:
  30. print('No use input...')
  31. if __name__ == '__main__':
  32. try:
  33. f = open('{}/data/info.d'.format(path))
  34. except:
  35. f = open('{}/data/info.d'.format(path), 'w')
  36. f.close()
  37. main()

文章到这里就结束了,感谢你的观看,下篇文章分享简易的计时器

为了感vb.net教程谢读c#教程者们,我想把我最近收python教程藏的一些编程干货分享给大家,回馈每一个读者,希望能帮到你们。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载