Python實現ssh登入執行shell命令並將結果寫入mysql資料庫
阿新 • • 發佈:2019-02-02
#coding=utf-8
import MySQLdb
import paramiko
import datetime
import time
#timestamp
ssh = paramiko.SSHClient()
#把要連線的機器新增到known_hosts檔案中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#連線伺服器
ssh.connect(hostname='127.0.0.1', port=22, username='root', password='123456')
memCmd = 'free -m | awk -F: '/Mem/' | awk '{print $3}''
#cmd = 'ls -l;ifconfig' #多個命令用;隔開
stdin, stdout, stderr = ssh.exec_command(memCmd)
memResult = stdout.read()
if not memResult:
memResult = stderr.read()
ssh.close()
#print(memResult.decode())
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='test123',
db ='test54',
)
cur = conn.cursor()
#建立資料表
#建立資料表
#cur.execute("create table meminfo(id int ,timestamp varchar(30),used varchar(20))")
#插入一條資料
#cur.execute("insert into meminfo values('1','%s','%s')" % (memResult,timestamp))
#修改查詢條件的資料
#cur.execute("update meminfo set used='0' where id = 0")
#刪除查詢條件的資料
#cur.execute("delete from meminfo")
cur.close()
conn.commit()
conn.close()
import MySQLdb
import paramiko
import datetime
import time
#timestamp
timestamp = time.mktime(datetime.datetime.now().timetuple())
#建立SSH物件ssh = paramiko.SSHClient()
#把要連線的機器新增到known_hosts檔案中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#連線伺服器
ssh.connect(hostname='127.0.0.1', port=22, username='root', password='123456')
memCmd = 'free -m | awk -F: '/Mem/' | awk '{print $3}''
#cmd = 'ls -l;ifconfig' #多個命令用;隔開
stdin, stdout, stderr = ssh.exec_command(memCmd)
memResult = stdout.read()
if not memResult:
memResult = stderr.read()
ssh.close()
#print(memResult.decode())
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='test123',
db ='test54',
)
cur = conn.cursor()
#建立資料表
#建立資料表
#cur.execute("create table meminfo(id int ,timestamp varchar(30),used varchar(20))")
#插入一條資料
#cur.execute("insert into meminfo values('1','%s','%s')" % (memResult,timestamp))
#修改查詢條件的資料
#cur.execute("update meminfo set used='0' where id = 0")
#刪除查詢條件的資料
#cur.execute("delete from meminfo")
cur.close()
conn.commit()
conn.close()