一、sshtunnel模块
ssh远程操作数据库:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48import os
import pymysql
import redis
from sshtunnel import SSHTunnelForwarder
# 1、远程连接mysql数据库:
with SSHTunnelForwarder(
ssh_address_or_host = ('60.200.188.199', 22), # 远端服务器地址和端口
ssh_username = 'admin', # ssh登录用户名
ssh_password = '123456', # ssh登录密码
remote_bind_address = ('127.0.0.1', 3320), # 绑定远端服务器mysql端口
local_bind_address=('127.0.0.1', 10220)) as server: # 绑定本地端口给pymysql交换数据用
#server.start() # 开启隧道,用with打开可以不用写
db = pymysql.connect(
host='localhost',
port=server.local_bind_port, # 和本地绑定的端口一致即可
user='root',
password='123456',
database='TestDB',
)
cursor = db.cursor()
update_vip_user_sql = """UPDATE vip_user SET expired_date='2018-10-31 00:00:00' WHERE user_id=25"""
select_vip_user_sql = """SELECT * FROM vip_user WHERE user_id=25"""
try:
cursor.execute(update_vip_user_sql)
cursor.execute(select_vip_user_sql)
vip_user_rows = cursor.fetchall()
for row in vip_user_rows:
print(row)
db.commit()
except Exception:
db.rollback()
finally:
cursor.close()
db.close()
#server.close() # 关闭隧道,用with打开可以不用写
# 2、远程连接redis数据库:
with SSHTunnelForwarder(
ssh_address_or_host = ('60.206.137.177', 22), # 远端服务器地址和端口
ssh_username = 'admin', # ssh登录用户名
ssh_password = '123456', # ssh登录密码
remote_bind_address = ('127.0.0.1', 6780)) as server: # 绑定远端服务器redis端口,也可以不用绑定本地端口
conn = redis.Redis(host='localhost', port=server.local_bind_port) # 和绑定的端口一直即可
conn.flushall() # 清除所有缓存
二、paramiko模块
ssh远程执行linux命令:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import os
import paramiko
# 3、远程执行linux命令:
ssh = paramiko.SSHClient() # 创建ssh客户端
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 把要连接的机器添加到known_hosts文件中
# 连接方式1,密码方式远程连接
ssh.connect(hostname='60.200.188.199', port=22, username='admin', password='123456', timeout=20)
cmd = "cd /data/ops/app/redis-2.8.17_media_6780/src/; ls -l redis-cli" # 多个命令用;隔开
# 连接方式2,互信方式远程连接
#key_file = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa")
#ssh.connect(sys_ip, 22, username=username, pkey=key_file, timeout=20)
#cmd = "cd /data/ops/app/redis-2.8.17_media_6780/src/; redis-cli -p 6780; flushall"
stdin, stdout, stderr = ssh.exec_command(cmd) # 执行命令
results = stdout.readlines() # 获取命令执行结果,返回的数据是一个list
print(results)
ssh.close()
持续更新…
最后更新: 2018年12月05日 10:12