简体   繁体   English

Python运行Linux命令

[英]Python to run Linux commands

I want to execute few linux commands using python these are my commands. 我想使用python执行一些linux命令,这些是我的命令。

modprobe ipv6
ip tunnel add he-ipv6 mode sit remote 216.218.221.6 local 117.211.75.3 ttl 255
ip link set he-ipv6 up
ip addr add 2001:470:18:f3::2/64 dev he-ipv6
ip route add ::/0 dev he-ipv6
ip -f inet6 addr

216.218.221.6 216.218.221.6
117.211.75.3 117.211.75.3
2001:470:18:f3::2/64 2001:470:18:F3 :: 2/64

these ip's are the inputs from the user. 这些IP是用户的输入。 Commands also need root privileges. 命令还需要root特权。 My Code upto now. 到目前为止的我的代码。

import os

print("Enter Server Ipv4 Address")
serverip4=input()

print("Enter Local Ipv4 Address")
localip4=input()

print("Enter Client Ipv6 Address")
clientip4=input()

Like this: 像这样:

import sys
import os
os.system("ip tunnel add he-ipv6 mode sit remote %s local %s ttl 255" % (whicheveripvariableisfirst), (whicheveripvariableisnext)))

If you need it run at sudo level then put sudo in the command section or make sure to run the python script as sudo. 如果需要以sudo级别运行它,则将sudo放在命令部分中,或确保以sudo身份运行python脚本。

I guess, subprocess would be best choice in this scenario as you want to get all command results and use it. 我想,在这种情况下,子进程将是最佳选择,因为您想获得所有命令结果并使用它。 You can refer this page for that: https://docs.python.org/2/library/subprocess.html 您可以为此参考该页面: https : //docs.python.org/2/library/subprocess.html

Here is the code: 这是代码:

import subprocess

#To use the sudo -> echo "password" | sudo <command>

ipv6_command_list = "echo 'password' | sudo 'ip tunnel add he-ipv6 mode sit remote 216.218.221.6 local 117.211.75.3 ttl 255'"
ip_link_list = "echo 'password' | sudo 'ip link set he-ipv6 up'"
ip_addr_list = "echo 'password' | sudo 'ip addr add 2001:470:18:f3::2/64 dev he-ipv6'"
ip_route_list = "echo 'password' |sudo 'ip route add ::/0 dev he-ipv6'"
ip_inet_list = "echo 'password' | sudo 'ip -f inet6 addr'"

for ip_command in [ip_link_list,ip_addr_list,ip_route_list,ip_inet_list]:
    proc = subprocess.check_output(ip_command, shell=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM