之前写了几次数据库连接和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()