RF工具自定義linux命令列命令執行程式碼及資料庫訪問
阿新 • • 發佈:2018-11-06
之前寫了幾次資料庫連線和linux命令列執行的程式碼,在此儲存下。
另考慮到python2的中文編碼問題,註釋等都用簡單英文,見諒~
import paramiko class Excsshcmd(): ssh = paramiko.SSHClient() def __init__(self): pass def ssh_login(self, hostname, username='root', password='123456', port=22): """ connect to spacial ssh service ip :param hostname: host ip :param username: login user :param password: login password :param port: connect port :return: """ Excsshcmd.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sshconn = Excsshcmd.ssh.connect(hostname=hostname, port=port, username=username, password=password) return sshconn def ssh_logout(self): """ close ssh connection :return: """ print('Closing SSH connection!') if Excsshcmd.ssh != None: Excsshcmd.ssh.close() def exc_cmd_and_return(self, exccmd): """ excute command line and return result :param exccmd: The excute command line :return: result """ stdin, stdout, stderr = Excsshcmd.ssh.exec_command(exccmd) stdin.write("Y") # Generally speaking, the first connection, need a simple interaction. Excsshcmd.ssh.exec_command(exccmd) rest = stdout.read() print rest return rest def exc_cmd(self, exccmd): """ only excute commandline :param exccmd: The excute command line :return: """ stdin, stdout, stderr = Excsshcmd.ssh.exec_command(exccmd) stdin.write("Y") # Generally speaking, the first connection, need a simple interaction. Excsshcmd.ssh.exec_command(exccmd) rest = stdout.read() print rest def excmysql(self, sqlcmd='', sqlfile='', sqluser='root', sqlhost='10.1.75.69', dbname='payment', sqlpassword='test123456', sqlport='3306'): """ use linux commandline to connect userdb and excute sql. sqlcmd or sqlfile used one of them! :param sqlcmd: :param sqlfile: :param sqluser: :param sqlhost: :param dbname: :param sqlpassword: :param sqlport: :return: """ if len(sqlcmd) > 1: sql = sqlcmd else: with open(sqlfile, 'r') as fp: sql = fp.read() execmd = "mysql -u %s -p%s -h%s -P%s -D%s -e '%s'" % (sqluser, sqlpassword, sqlhost, sqlport, dbname, sql) print(execmd) stdin, stdout, stderr = Excsshcmd.ssh.exec_command(execmd) rest = stdout.read() print rest if __name__ == '__main__': esc = Excsshcmd() esc.ssh_login('1.1.1.1', username='root', password='123456') esc.exc_cmd_and_return('ls /usr/local') esc.excmysql(sqlcmd='show databases', sqlhost='1.1.1.1', sqlpassword='123456') esc.ssh_logout()