2016-10-05 00:51:08 +00:00
|
|
|
import os, sys
|
2016-09-10 07:04:55 +00:00
|
|
|
import subprocess as sp
|
|
|
|
|
|
|
|
|
|
|
|
def shell(cmd):
|
|
|
|
"""Run each line of a shell script; raise an exception if any line returns
|
|
|
|
a nonzero value.
|
|
|
|
"""
|
|
|
|
pin, pout = os.pipe()
|
2016-10-05 16:24:24 +00:00
|
|
|
proc = sp.Popen('/bin/bash', stdin=sp.PIPE)
|
2016-09-10 07:04:55 +00:00
|
|
|
for line in cmd.split('\n'):
|
|
|
|
line = line.strip()
|
|
|
|
if line.startswith('#'):
|
2016-10-17 16:20:27 +00:00
|
|
|
print('\033[33m> ' + line + '\033[0m')
|
2016-09-10 07:04:55 +00:00
|
|
|
else:
|
2016-10-17 16:20:27 +00:00
|
|
|
print('\033[32m> ' + line + '\033[0m')
|
2016-09-10 07:04:55 +00:00
|
|
|
if line.startswith('cd '):
|
|
|
|
os.chdir(line[3:])
|
2016-10-17 16:20:27 +00:00
|
|
|
proc.stdin.write((line + '\n').encode('utf-8'))
|
|
|
|
proc.stdin.write(('echo $? 1>&%d\n' % pout).encode('utf-8'))
|
2016-09-10 07:04:55 +00:00
|
|
|
ret = ""
|
|
|
|
while not ret.endswith('\n'):
|
|
|
|
ret += os.read(pin, 1)
|
|
|
|
ret = int(ret.strip())
|
|
|
|
if ret != 0:
|
2016-10-17 16:20:27 +00:00
|
|
|
print("\033[31mLast command returned %d; bailing out.\033[0m" % ret)
|
2016-09-10 07:04:55 +00:00
|
|
|
sys.exit(-1)
|
|
|
|
proc.stdin.close()
|
|
|
|
proc.wait()
|
|
|
|
|
|
|
|
|
|
|
|
def ssh(host, cmd):
|
|
|
|
"""Run commands on a remote host by ssh.
|
|
|
|
"""
|
|
|
|
proc = sp.Popen(['ssh', host], stdin=sp.PIPE)
|
|
|
|
proc.stdin.write(cmd)
|
|
|
|
proc.wait()
|
|
|
|
|