Share an instance of using Python to write an automatic SSH login to a remote server

Source: Internet
Author: User
Many times we prefer to SSH to a Linux server directly at the terminal of our own computer, rather than using a tool area with a UI interface to connect to our servers. But in the terminal using SSH we need to enter the account number and password every time, this is also a worry, so we can easily build a linux/mac os running automatic SSH login remote server gadget.
Let's start with an animated GIF example:

Overview

Let's take a look at what we need:

1. Add/Remove IP, port, password 2 required for the connection server. Automatically enter a password to log on to a remote server

Yes, we're going to do this simple function.

Start writing code
The code is long, so I also put it on GitHub and the code cloud, at the bottom of the article:
1. We build a module directory osnssh (Open source noob ssh), and then build two more directories below, one used to put the main program named Bin Bar, a used to save the login data (IP, port, password) is called the Information Bar.

-osnssh    -bin    -data

1. Setup program: Add/Remove IP, port, password. Build a py file bin/setting.py:

#!/usr/bin/env Python#-*-coding:utf-8-*-import Re, base64, OS, Syspath = Os.path.dirname (Os.path.abspath (sys.argv[0)) ) ' option configuration management __author__ = ' Allen Woo ' ' Def Add_host_main (): While 1:if add_host (): Break Print ("\n\nagain:") def Add_hos T (): "Add host Information: return:" Print ("================add=====================") print ("[Help]input ' #q ' exit ") # input 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 # Input Port Host_port = Str_format (" Host port (Default): "," [0-9]+ ") if Host_port = =" #q ": RET Urn # Enter password password = str_format ("Password:", ". *") if password = = "#q": Return # password Encryption password = Base64.encodestrin g (password) # enter username name = Str_format ("User name:", "^[^]+$") if name = = "#q": Return 1elif not Name:os.system ("C Lear ") Print (" [Warning]:user name Cannot be Emptyg ") return 0# the alias# entry alias alias = Str_format (" Local alias: "," ^[^]+$ ") If alias = =" #q ": Return 1elif Not Alias:os.system ("clear") print ("[Warning]:alias cannot is Emptyg") return 0# Open Data Save file of = Open ("{}/ DATA/INFORMATION.D ". Format (path)) hosts = Of.readlines () # traverses the file data to find out if there is an IP, port, and alias 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 0if alias = = L_list[4]:    Os.system ("clear") print ("[Warning]alias ' {} ' existing". Format (Alias)) return 0 of.close () # save# save data to data file of = open ("{}/DATA/INFORMATION.D". Format (path), "a") Of.write ("\n{} {} {} {} {}". Format (Name.strip ("\ n"), Host_ip.str IP ("\ 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 1def remove_host (): "' Delete host information: return:         "While 1:# Open data file 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# traversal output so the information (except the password) is chosen for the For I in range (0, L): if not Hosts[i].stri P (): 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 (hos  Ts[i]) hosts = hosts_temp[:] Print ("+{}+". Format ("-" *40)) C = Raw_input ("[Remove]choose the number or Alias (' #q ' to exit): "Is_aLias = False is_y = falsetry:c = Int (c) If C > L or C < 1:os.system ("clear") Print ("[Warning]:there is No") Continuedel hosts[c-1] is_y = Trueexcept:is_alias = Trueif Is_alias:if C.strip () = = "#q": Os.system ("clear") Break n = 0for L in hosts:if c.strip () = = L.s Plit ("") [4].strip ():d el Hosts[n] is_y = True N + = 1if not Is_y:os.system (" Clear ") Print (" [Warning]:there is No ") Continueelse: # save# confirm again whether to remove 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):" To validate the input data format:p Aram lable::p Aram rule:: Return: "While 1:print (" {} (' #q ' exit) ". Format (lable)) temp = Raw_input (). Strip () m = Re.match (r "{}". Format (rule), temp) if M:breakelif "Port" in lable:temp = 22breakelif temp. Strip () = = "#q": Os.system ("clear") Break Os.system ("clear") print ("[Warning]:invalid format") Retu RN Temp

2. We add a function in setting.py to output our information, that is, about me.

def about (): "    output information about this program    : return:"    = 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 in the bin directory About.dat write some of our information, such as:

{"Auther": "Allen Woo", "Introduction": "in Linux or MAC using SSH, does 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 "}

Okay, here's the Setup program:

2. Automatically log on to the remote server program: Build a PY file in the bin called auto_ssh.py:
Note: Here we need to install a package called: pexpect, User terminal interaction, capture interactive information implementation automatically enter the password.
Install Pexpect:

Pip Install Pexpect

Then start writing code:

#!/usr/bin/env python#-*-coding:utf-8-*-import OS, sys, base64import pexpectpath = Os.path.dirname (Os.path.abspath ( SYS.ARGV[0]) def choose (): # Open Our data file of = open ("{}/DATA/INFORMATION.D". Format (path)) hosts = Of.readlines () host S_temp = []for h in Hosts:if H.strip (): Hosts_temp.append (h) hosts = hosts_temp[:] L = Len (hosts) if L &LT = 0:os.system ("clear") print ("[Warning]please Add the Host Server") Returnwhile 1:print ("==========     =======ssh=================== ") Print (" +{}+ ". Format ("-"*40)) Print (" | Alias Username@ip:port ") for I in range (0, l): V_list = Hosts[i].strip (). Split (" ") Print (" +{}+ ". Fo Rmat ("-" *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 (' #q ' exit):") Is_alias = False is_y = falsetry:c = Int (c ) if C > L or C < 1:               Os.system ("clear") print ("[Warning]:there is No") Continue l_list = HOSTS[C-1].SPL It ("") name = l_list[0] host = l_list[1] port = l_list[2] Password = l_list[3 ] Is_y = Trueexcept:is_alias = Trueif is_alias:if c.strip () = = "#q": Os.system ("Clea                    R ") Returnfor 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 = Trueif not is_y:continue# ssh# decrypt encrypted saved password Password = base64.decodestring (passwo            RD) Print ("In the Connection ...") # Prepare remote connection, stitching Ip:port print ("{}@{}". Format (name, host)) if Port = = "22": Connection ("SSH {}@{}". Format (name, host), password) else:connection ("SSH {}@{}:{}". Format (name, host, Por t), password) def connectIon (CMD, pwd): ' Connect remote server:p aram cmd::p Aram pwd:: ' Return: ' ' child = pexpect.spawn (cmd) i = Chil D.expect ([". *password.*", ". *continue.*?", Pexpect. EOF, Pexpect. TIMEOUT]) if (i = = 0): # If it appears in the interaction. *password.*, just ask us to enter the password # We'll fill it in automatically. Child.sendline ("{}\n". Format (PWD)) child . Interact () elif (i = = 1): # If the interactive prompt is continued, the first connection will usually appear # this time we send "yes" and then automatically enter the password child.sendline ("yes\n") Child.sen Dline ("{}\n". Format (PWD)) #child. Interact () else:# Connection failed print ("[Error]the connection Fails")

OK, now we just need to start the file, that is, the first menu after opening the program
3. Osnssh directory to build a osnssh.py file:

#!/usr/bin/env python#-*-coding:utf-8-*-import OS, Syssys.path.append (".. /") From bin import setting, Auto_sshpath = Os.path.dirname (Os.path.abspath (sys.argv[0]))" is convenient to use SSH on Linux terminal, save used IP:         PORT, password automatic login __author__ = ' Allen Woo ' 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 ") 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 __na me__ = = ' __main__ ': try:of = open ("{}/DATA/INFORMATION.D". Format (path)) Except:of = Open ("{}/data/informatio N.D ". FoRmat (Path), "W") Of.close () main () 

Finally finished, we can try it:

$python osnssh.py

The concrete demonstration, is I put a GIF animated picture at the beginning of the article add a group of source code

You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
626062078, we learn python! together.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.