栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python连接Linux虚拟机发送并执行命令

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python连接Linux虚拟机发送并执行命令

一、Pycharm SSH Session

在tool中点击Start SSH Session


二、Pycharm Remote Host

在其中的Type选中SFTP。
在SSH configuration配置齐全。

修改Web server URL
然后可以测试一下连接

最后点击OK

最后可以在侧栏的Remote Host中查看到连接的虚拟机文件信息

三、代码连接
import paramiko

# 连接并执行命令的函数
def connetAndExec(hostname,username,password,order):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接虚拟机
    ssh.connect(hostname,22,username,password)
    # 按行执行命令
    for line in order:
        ssh.exec_command(line)
    # 连接关闭
    ssh.close()

def myCommand():
	# 开启你想执行的命令行文件
    file = open("command.txt", "r")
    # 读取命令
    order = file.read()
    # connetAndExec("192.168.10.130", "root", "hjfhjf0501", order)
    connetAndExec("你的地址", "你的登录名", "你的密码", order)

if __name__ == '__main__':
    myCommand()

command.txt的文件格式如下(示例,应需要改变):

sync;
/etc/init.d/postgresql stop;
echo 1 > /proc/sys/vm/drop_caches;
/etc/init.d/postgresql start;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1034248.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号