Python结构 - 运行方法尚未完成 [英] Python fabric - run method is not being finished

查看:170
本文介绍了Python结构 - 运行方法尚未完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我准备了一段代码,其目的是以root用户身份登录。

我不能使用sudo方法因为我不想在系统上存在我想控制和直接记录root是不可能的。我的想法是以admin用户身份登录,然后使用su命令切换到root用户。



以下部分包含几乎正常工作的代码为了我。任何想法如何解决?在此先感谢:)



我尝试过:



我的环境:

Python 3.7

布料2.4.0



代码:

Hi There,
I've prepared a piece of code, which intention is to log as a root user.
I can't use "sudo" method because that is not existing on the system that i want to control and logging directly as "root" is impossible. My idea is to log as a "admin" user and then use "su" command to switch to "root" user.

Section below contains code that is almost working for me. Any ideas how to solve that? Thanks in advance:)

What I have tried:

My environment:
Python 3.7
Fabric 2.4.0

Code:

from fabric import Connection
from invoke import Responder

sudopass = Responder(pattern=r'Password:', response='adminPassword\n')

with Connection('192.168.0.106', user="admin", port=22, connect_kwargs={"password": "admin"}) as dss:
    command = "uname -s"
    print("Response on {} is: {}".format(command, dss.run(command)))
    command = "whoami"
    print("Response on {} is: {}".format(command, dss.run(command)))
    command = "su"
    print("Response on {} is after executing su command: {}".format(command,
                                                                    dss.run(command, pty=True, watchers=[sudopass])))
    command = "whoami"
    print("Response on {} is: {}".format(command, dss.run(command)))
print("Script end")





输出:



Output:

Linux
Response on uname -s is: Command exited with status 0.
=== stdout ===
Linux

(no stderr)
dssadmin
Response on whoami is: Command exited with status 0.
=== stdout ===
dssadmin

(no stderr)
Password: 
/home/dssadmin # 





正如你所看到的,发送su命令后脚本卡住了。



As you can see script got stuck after sending "su" command.

推荐答案

我找到了解决方案:

I've found solution:
sudopass = Responder(pattern=r'Password:', response='admin__password\n')

def su(connection, command) -> int:
    return connection.run(f"su -c '{command}'", pty=True, watchers=[sudopass])







with Connection('192.168.0.106', user="dssadmin", port=22, connect_kwargs={"password": "password"}) as ssh_connection:
    command = "uname -s"
    print("Response on {} is: {}".format(command, ssh_connection.run(command)))
    command = "whoami"
    print("Response on {} is: {}".format(command, ssh_connection.run(command)))
    command = "opkg update"
    print("Response on {} is after executing su command: {}".format(command, su(ssh_connection, command)))
   command = "opkg install rescue-utils"
    print("Response on {} is after executing su command: {}".format(command, su(ssh_connection, command)))
    command = "whoami"
    print("Response on {} is: {}".format(command, su(dss, command)))
print("Script end")


这篇关于Python结构 - 运行方法尚未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆