#!/usr/bin/env python
#coding=utf-8

import os
import pexpect
import client

def ssh_cmd(ip,port,user, passwd, cmd):
    ssh = pexpect.spawn('ssh %s@%s -p%s "%s"' % (user,ip,port, cmd))
    try:
        i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
        if i == 0 :
            ssh.sendline(passwd)
        elif i == 1:
            ssh.sendline('yes')
            ssh.expect('password:')
            ssh.sendline(passwd)
        #ssh.sendline(cmd)
        ssh.expect(pexpect.EOF)
        return 1
    except pexpect.EOF:
        print "EOF"
        ssh.close()
        ret = -1
    except pexpect.TIMEOUT:
        print "TIMEOUT"
        ssh.close()
        ret = -2
    return ret

def scp_cmd(ip,port,user,passwd,filename):
    ret= 0
    scp=pexpect.spawn('scp -P%s %s %s@%s:/script' % (port,filename,user,ip))
    index = scp.expect(['','password:'],timeout=5)
    if(index==0 or index==1):
        scp.sendline(passwd)
        #scp.expect(pexpect.EOF)
        ret = 1
    return ret

def remote_run(ip,port,user,passwd,filepath):
    scp_cmd(ip,port,user,passwd,os.path.join(os.path.dirname(__file__),'server.py'))
    ssh_cmd(ip,port,user,passwd,'chmod 755 server.py');
    ssh_cmd(ip,port,user,passwd,'./server.py')
    scp_cmd(ip,port,user,passwd,filepath)
    filename=os.path.basename(filepath)
    ssh_cmd(ip,port,user,passwd,'chmod 755 '+filename);
    result=client.socket_send(ip,filename)
    return result
    

if __name__ == "__main__":
    ip='10.214.144.182'
    user='root'
    port='22'
    passwd='#srv@309'
    script='script'
    if scp_cmd(ip,port,user,passwd,os.path.join(os.path.dirname(__file__),'server.py')):
    	print("server.py传输成功")
    if (ssh_cmd(ip,port,user,passwd,'chmod 755 server.py') == 1):
    	print ("server.py权限修改成功")
    if (ssh_cmd(ip,port,user,passwd,'./server.py') == 1):
    	print("远端服务程序开始执行")
    if scp_cmd(ip,port,user,passwd,os.path.join(os.path.dirname(__file__),script)):
    	print("脚本发送成功")
    if ssh_cmd(ip,port,user,passwd,'chmod 755 '+script):
    	print("脚本权限修改成功")

    print("开始执行脚本")
    result=client.socket_send(ip,'script')
    print("打印结果:")
    print(result)
