#!/usr/bin/python
# 导入各种模块
import sys
...
# 各种变量
consul_ip = sys.argv[2]
install_path = ...
...
# 使用os.system()在python执行shell命令
os.system('mkdir -p '+install_path)
...
# 进一步对变量进行处理成 “export install_path= /opt” 形式
def create_env_str(env_dict):
import pdb
pdb.set_trace()
env_str = ""
for k, v in env_dict.items():
env_str = env_str + "export " + k + "=" + v + "\n"
return env_str
# 将变量设置成字典,以便传递到shell脚本中使用
env_dict = {
"install_path": install_path,
"current_dir": current_dir,
"req_path": req_path,
"deps_path": deps_path,
"packages": packages,
"log_path": log_path,
"consul_ip": sys.argv[2]
}
# 创建可执行shell脚本
def gen_script_fire(env_dict):
env = create_env_str(env_dict)
# shell中要执行的具体的指令
cmd = '''
#此处是往“/tmp/vmware-exporter-systemctl”文件中写内容,配置服务
sudo cat >/tmp/vmware-exporter-systemctl<<EOF
[Unit]
Description=Vmware Exporter
After=network.target
[Service]
ExecStart=/usr/bin/python ${install_path}/vmware_exporter/vmware_exporter/vmware_exporter.py -c ${consul_ip}
[Install]
WantedBy=default.target
EOF
...
'''
# 开始写
with open('/tmp/service_firewalld.sh', 'w+') as f:
f.write("#!/bin/bash" + "\n")
f.write(env)
f.write(cmd)
def run(cmd):
# 用subprocess.call 方法执行shell脚本
ret = subprocess.call(cmd, shell=True)
if ret != 0:
sys.exit('Exec cmd %s error, return value: %s' % (cmd, str(ret)))
def run_script():
run("sudo bash /tmp/service_firewalld.sh")
gen_script_fire(env_dict)
run_script()
注意:
cmd= ”’ ”’ 中有expect命令时,可能出现expect spawn not found
错误
原因:expec不是shell中的命令,所以在执行bash shellname.sh
时会报错
解决:参考:http://blog.csdn.net/chinabluexfw/article/details/7461944
1. 不用bash
或sh
执行shell脚本,使用./shellname.sh
命令执行
2. 使用chmod +x shellname.sh
赋权限