search
HomeBackend DevelopmentPython TutorialHow to use python to write a small tool code for automatic SSH login to a remote server (recommended)

The following editor will bring you a small tool (example) to write an automatic SSH login to a remote server using python. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

Many times we like to connect to the Linux server through ssh directly from the terminal of our computer, rather than using the tool area with UI interface to connect to our server. However, when using ssh in the terminal, we need to enter the account number and password every time, which is also a worry, so we can simply create a small tool that runs on Linux/Mac os to automatically log in to the remote server through ssh.

Let’s give an example of a GIF animation:

## Overview

Let’s first sort out what functions we need:

1. Add/delete the IP, port, and password required to connect to the server

2. Automatically enter the password to log in to the remote server

Yes, we will do such a simple function

Start writing code

The code is relatively long, so I also put it on Github and Code Cloud. The address is at the bottom of the article:

1. Let’s build a module Directory osnssh (Open source noob ssh), and then create two more directories below, one is used to store the main program and is called bin, and the other is used to save login data (IP, port, password) and is called data.

-osnssh

-bin
-data

1. Setting program: add/delete IP, port, password. Create py file bin/setting.py:


#!/usr/bin/env python
#-*-coding:utf-8-*-
import re, base64, os, sys
path = os.path.dirname(os.path.abspath(sys.argv[0]))
'''

选项配置管理

author = 'allen woo'
'''
def add_host_main():
 while 1:
  if add_host():
   break
  print("\n\nAgain:")

def add_host():
 '''
 添加主机信息
 :return: 
 '''
 print("================Add=====================")
 print("[Help]Input '#q' exit")
 # 输入IP
 host_ip = str_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])$")
 if host_ip == "#q":
  return 1
 # 输入端口
 host_port = str_format("Host port(Default 22):", "[0-9]+")
 if host_port == "#q":
  return 1
 # 输入密码
 password = str_format("Password:", ".*")
 if password == "#q":
  return 1
 # 密码加密
 password = base64.encodestring(password)
 # 输入用户名
 name = str_format("User Name:", "^[^ ]+$")
 if name == "#q":
  return 1
 elif not name:
  os.system("clear")
  print("[Warning]:User name cannot be emptyg")
  return 0

 # The alias
 # 输入别名
 alias = str_format("Local Alias:", "^[^ ]+$")
 if alias == "#q":
  return 1
 elif not alias:
  os.system("clear")
  print("[Warning]:Alias cannot be emptyg")
  return 0
 # 打开数据保存文件
 of = open("{}/data/information.d".format(path))
 hosts = of.readlines()
 # 遍历文件数据,查找是否有存在的Ip,端口,还有别名
 for l in hosts:
  l = l.strip("\n")
  if not l:
   continue
  l_list = l.split(" ")
  if host_ip == l_list[1] and host_port == l_list[2]:
   os.system("clear")
   print("[Warning]{}:{} existing".format(host_ip, host_port))
   return 0
  if alias == l_list[4]:
   os.system("clear")
   print("[Warning]Alias '{}' existing".format(alias))
   return 0
 of.close()
 # save
 # 保存数据到数据文件
 of = open("{}/data/information.d".format(path), "a")
 of.write("\n{} {} {} {} {}".format(name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n"), alias.strip("\n")))
 of.close()
 print("Add the success:{} {}@{}:{}".format(alias.strip("\n"), name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n")))
 return 1

def remove_host():
 '''
 删除主机信息
 :return: 
 '''
 while 1:
  # 打开数据文件
  of = open("{}/data/information.d".format(path))
  hosts = of.readlines()
  of.close
  l = len(hosts)
  if l <= 0:
   os.system("clear")
   print("[Warning]There is no host")
   return

  print("================Remove================")
  print("+{}+".format("-"*40))
  print("|  Alias UserName@IP:PORT")
  hosts_temp = []
  n = 0
  # 遍历输出所以信息(除了密码)供选择
  for i in range(0, l):
   if not hosts[i].strip():
    continue
   v_list = hosts[i].strip().split(" ")
   print("+{}+".format("-"*40))
   print("| {} | {} {}@{}:{}".format(n+1, v_list[4], v_list[0], v_list[1], v_list[2]))
   n += 1
   hosts_temp.append(hosts[i])
  hosts = hosts_temp[:]
  print("+{}+".format("-"*40))
  c = raw_input("[Remove]Choose the Number or Alias(&#39;#q&#39; to exit):")
  is_alias = False
  is_y = False
  try:
   c = int(c)
   if c > l or c < 1:
    os.system("clear")
    print("[Warning]:There is no")
    continue
   del hosts[c-1]
   is_y = True

  except:
   is_alias = True
  if is_alias:
   if c.strip() == "#q":
    os.system("clear")
    break 
   n = 0
   for l in hosts:
    if c.strip() == l.split(" ")[4].strip():
     del hosts[n]
     is_y = True 
    n += 1
  if not is_y:
   os.system("clear")
   print("[Warning]:There is no")
   continue
  else: 
   # save
   # 再次确认是否删除
   c = raw_input("Remove?[y/n]:")
   if c.strip().upper() == "Y":
    of = open("{}/data/information.d".format(path), "w")
    for l in hosts:
     of.write(l)
    print("Remove the success!")
    of.close()

def str_format(lable, rule):
 &#39;&#39;&#39;
 用于验证输入的数据格式
 :param lable: 
 :param rule: 
 :return: 
 &#39;&#39;&#39;
 while 1:
  print("{} (&#39;#q&#39; exit)".format(lable))
  temp = raw_input().strip()
  m = re.match(r"{}".format(rule), temp)
  if m:
   break
  elif "port" in lable:
   temp = 22
   break
  elif temp.strip() == "#q":
   os.system("clear")
   break
  os.system("clear")
  print("[Warning]:Invalid format")

 return temp

2. Let’s add another function in setting.py to output our information, which is about me.


def about():
 &#39;&#39;&#39;
 输出关于这个程序的信息
 :return: 
 &#39;&#39;&#39;
 of = open("{}/bin/about.dat".format(path))
 rf = of.read()
 try:
  info = eval(rf)
  os.system("clear")
  print("================About osnssh================")
  for k,v in info.items():
   print("{}: {}".format(k, v))
 except:
  print("For failure.")
 return

Then create a file about.dat under the bin directory and write some of our information, such as:


{
 "auther":"Allen Woo",
 "Introduction":"In Linux or MAC using SSH, do not need to enter the IP and password for many times",
 "Home page":"",
 "Download address":"https://github.com/osnoob/osnssh",
 "version":"1.1.0",
 "email":"xiaopingwoo@163.com"
}

That’s it for setting up the program:

2. Automatically log in to the remote server program: Create a py file in bin called auto_ssh.py:

Note: Here we need to first Install a package called: pexpect, which allows user terminal interaction to capture interaction information and automatically enter passwords.

Install pexpect:

pip install pexpect


Then start writing code:


#!/usr/bin/env python
#-*-coding:utf-8-*-
import os, sys, base64
import pexpect
path = os.path.dirname(os.path.abspath(sys.argv[0]))

def choose():
 # 打开我们的数据文件
 of = open("{}/data/information.d".format(path))
 hosts = of.readlines()
 hosts_temp = []
 for h in hosts:
  if h.strip():
   hosts_temp.append(h)
 hosts = hosts_temp[:]
 l = len(hosts)
 if l <= 0:
  os.system("clear")
  print("[Warning]Please add the host server")
  return
 while 1:

  print("=================SSH===================")
  print("+{}+".format("-"*40))
  print("|  Alias UserName@IP:PORT")
  for i in range(0, l):
   v_list = hosts[i].strip().split(" ")
   print("+{}+".format("-"*40))
   print("| {} | {} {}@{}:{}".format(i+1, v_list[4], v_list[0], v_list[1], v_list[2]))
  print("+{}+".format("-"*40))
  c = raw_input("[SSH]Choose the number or alias(&#39;#q&#39; exit):")
  is_alias = False
  is_y = False
  try:
   c = int(c)
   if c > l or c < 1:
    os.system("clear")
    print("[Warning]:There is no")
    continue
   l_list = hosts[c-1].split(" ")
   name = l_list[0]
   host = l_list[1]
   port = l_list[2]
   password = l_list[3]
   is_y = True

  except:
   is_alias = True
  if is_alias:
   if c.strip() == "#q":
    os.system("clear")
    return
   for h in hosts:
    if c.strip() == h.split(" ")[4].strip():
     l_list = h.split(" ")
     name = l_list[0]
     host = l_list[1]
     port = l_list[2]
     password = l_list[3]
     is_y = True
  if not is_y:
   continue
  # ssh
  # 将加密保存的密码解密
  password = base64.decodestring(password)
  print("In the connection...")
  # 准备远程连接,拼接ip:port
  print("{}@{}".format(name, host))
  if port == "22":
   connection("ssh {}@{}".format(name, host), password)

  else:
   connection("ssh {}@{}:{}".format(name, host, port), password)

def connection(cmd, pwd):
 &#39;&#39;&#39;
 连接远程服务器
 :param cmd: 
 :param pwd: 
 :return: 
 &#39;&#39;&#39;
 child = pexpect.spawn(cmd)
 i = child.expect([".*password.*", ".*continue.*?", pexpect.EOF, pexpect.TIMEOUT])
 if( i == 0 ):
  # 如果交互中出现.*password.*,就是叫我们输入密码
  # 我们就把密码自动填入下去
  child.sendline("{}\n".format(pwd))
  child.interact()
 elif( i == 1):
  # 如果交互提示是否继续,一般第一次连接时会出现
  # 这个时候我们发送"yes",然后再自动输入密码
  child.sendline("yes\n")
  child.sendline("{}\n".format(pwd))

  #child.interact() 
 else:
  # 连接失败
  print("[Error]The connection fails")

Okay, now we only need to start the file, which is the first menu after opening the program

3. Create an osnssh.py file in the osnssh directory:


#!/usr/bin/env python
#-*-coding:utf-8-*-
import os, sys
sys.path.append("../")
from bin import setting, auto_ssh
path = os.path.dirname(os.path.abspath(sys.argv[0]))
&#39;&#39;&#39;
方便在LINUX终端使用ssh,保存使用的IP:PORT , PASSWORD
自动登录
author = &#39;allen woo&#39;
&#39;&#39;&#39;
def main():
 while 1:

  print("==============OSNSSH [Menu]=============")
  print("1.Connection between a host\n2.Add host\n3.Remove host\n4.About\n[Help]: q:quit clear:clear screen")
  print("="*40)
  c = raw_input("Please select a:")
  if c == 1 or c == "1":
   auto_ssh.choose()
  if c == 2 or c == "2":
   setting.add_host_main()
  if c == 3 or c == "3":
   setting.remove_host()
  if c == 4 or c == "4":
   setting.about()
  elif c == "clear":
   os.system("clear")
  elif c == "q" or c == "Q" or c == "quit":
   print("Bye")
   sys.exit()
  else:
   print("\n")

if name == &#39;main&#39;:
 try:
  of = open("{}/data/information.d".format(path))
 except:
  of = open("{}/data/information.d".format(path), "w")
 of.close()
 main()

Finally finished writing, we can give it a try:

$python osnssh.py

The above is the detailed content of How to use python to write a small tool code for automatic SSH login to a remote server (recommended). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool