Python stepping stone

Source: Internet
Author: User

The company has more than 1000 servers, and the online machines are not allowed to log on to the root account. Therefore, common users are usually logged on, and then su to root. The passwords are stored in the excel table, in this way, it is very troublesome to log on to a machine, enter two commands, and search for two passwords. In addition, the password table is not easy to control, so you can put the password in the database, every time I log on to the ssh client, I automatically check the password in the database, and then send the password for interaction. This facilitates us and controls the password. The core of the script is to use pexpect for interaction, use MySQLdb to query the password, save the code as zssh, give the execution permission, create a database, and import the password table into the database. Then, you can log on using the zssh ip address. Is it great, come and try it!

Usage of pexpect to look at http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/

See attachment for code

The Code is as follows:

#! /Usr/local/bin/python # coding: UTF-8 ## import module import osimport sysimport pexpectimport MySQLdbimport structimport fcntlimport termiosimport signal # input parameter opt = sys. argv # if the parameter is not followed, the prompt is if len (opt) = 1: print ''' ---------------------------- 'useage :. /zssh. py serverip' ---------------------------- ''' sys. exit (2) ## the following two functions change the size of the pexpect simulated window, ## see http://guweigang.com/blog/2012/10/25/using-python-ssh-landing-module-performs-pexpect/def sigwinch_passthrough (sig, data): winsize = getwinsize () global foo. setwinsize (winsize [0], winsize [1]) def getwinsize (): if 'tiocgwinsz 'in dir (termios): TIOCGWINSZ = termios. TIOCGWINSZ else: TIOCGWINSZ = 1074295912L # Assume s = struct. pack ('hhhh', 0, 0, 0, 0) x = fcntl. ioctl (sys. stdout. fileno (), TIOCGWINSZ, s) return struct. unpack ('hhhh', x) [0: 2] # input ipip = opt [1] # connect to mysqlconn = MySQLdb using the MySQLdb driver. connect (host = 'localhost', user = 'root', passwd = 'te62s # ^ t', db = 'sa ') cursor = select cute ('select muser, mpass, rpass from password where ip = % s', ip) result = cursor. fetchall () # if the ip address is not found in the database, the user is prompted to input and save the ip address. if the ip address is found, connect to if len (result) = 0: muser = raw_input ('input User name: ') mpass = raw_input ('enter User Password:') rpass = raw_input ('enter root Password :') cursor.exe cute ('insert into password values (% s, % s) ', (ip, muser, mpass, rpass) conn. commit () elif len (result) = 1: muser = result [0] [0] mpass = result [0] [1] rpass = result [0] [2] # Use the spawn class of the pexpect module, connect sshfoo = pexpect. spawn ('ssh % s @ % s' % (muser, ip) while True: # expected index = foo. CT (['contine', 'assword', pexpect. EOF, pexpect. TIMEOUT], timeout = 10) # if the result is continue, that is, if yes/no is input for the first connection, send yes if index = 0: foo. sendline ('yes') continue # If you are prompted to enter a password, send the password elif index = 1: foo. sendline (mpass) # There are two cases after the password is sent: Successful Logon or incorrect password index2 = foo. CT (['Password', '] \ $']) # if the password is correct, if index2 = 1: print '% s logon succeeded' % muser break # if the password is incorrect, the system prompts you to enter the password elif index2 = 0: while True: muser = raw_input ('enter User name :') mpass = raw_input ('user password incorrect, re-enter: ') foo. sendline (mpass) index3 = foo. CT (['] \ $', 'assword'], timeout = 5) # if the password is correct, save it to the database if index3 = 0: cursor.exe cute ('Update sys_pass set muser = % s, mpass = % s where ip = % s', (muser, mpass, ip) conn. commit () foo. sendline ('') break # if not, recycle else: continue else: print 'Connection timeout' break # The following su to root is similar to while True: foo. CT ('$') foo. sendline ('Su-root') # index4 = foo. CT (['Password', 'Password', 'assword', pexpect. TIMEOUT, pexpect. EOF], timeout = 5) foo. sendline (rpass) index5 = foo. CT (['] #', 'Monitor ', pexpect. EOF, pexpect. TIMEOUT], timeout = 5) if index5 = 0: print 'root logon successful 'foo. sendline ('') break elif index5 = 1: while True: rpass = raw_input ('root password incorrect, enter: ') foo. CT ('$') foo. sendline ('Su-root') # index6 = foo. CT (['Password', 'Password', 'assword', pexpect. TIMEOUT, pexpect. EOF], timeout = 5) foo. sendline (rpass) index7 = foo. CT (['] #', 'Monitor ', pexpect. EOF, pexpect. TIMEOUT], timeout = 5) if index7 = 0: cursor.exe cute ('Update sys_pass set rpass = % s where ip = % s', (rpass, ip) conn. commit () print 'root logon successful 'break elif index7 = 1: continue else: print 'error' else: print 'error' # use the two functions to adjust the size of the subthread window signal. signal (signal. SIGWINCH, sigwinch_passthrough) size = getwinsize () foo. setwinsize (size [0], size [1]) # Enter interact interactive mode foo. interact () pass


 

Database creation

create database sa;create table password (ip varchar(15) primary key not null, muser varchar(15), mpass varchar(30), rpass varchar(30));


 

Insert the ip address, common user name, password, and root password in the password table into the database. I use a script.

#!/usr/local/bin/pythonimport MySQLdbconn = MySQLdb.connect(host='localhost', user='root', passwd='Te62S#^t', db='sa')cursor = conn.cursor()f = open('passwd.txt')num = 0for i in f:    ilist = i.split()    if len(ilist) == 4:        ip = ilist[0]        muser = ilist[1]        mpass = ilist[2]        rpass = ilist[3]        try:            cursor.execute('insert into password values (%s,%s,%s,%s)', (ip, muser, mpass, rpass))            num += 1        except:            passprint num                                                                                                                            conn.commit()cursor.close()conn.commit()
 
 

Save the password to the format below the passwd.txt format class and execute the script.

Common IP user name and password root Password

202.106.0.20 monitor asdf123Sfad f (adfasdfasdf

202.106.0.21 zhswred hathell oworld




This article from the "Free Linux, Share Linux" blog, please be sure to keep this source http://laoguang.blog.51cto.com/6013350/1328891

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.