I have written basic port scanner for target ip and when I run it through kali vm it says sh: 1: nmap-F192.168.234.135: not found. but when I run nmap -F 192.168.234.135 ... its perfectly working. Can anyone point out the reason behind it. thanks
import os
def get_nmap(options,ip):
command = "nmap" + options + "" + ip
process = os.popen(command)
result = str(process.read())
return result
print(get_nmap('-F','192.168.234.135'))
Better, using the subprocess module:
def get_nmap(options, ip) :
return subprocess.check_output(["nmap", options, ip])
#end get_nmap
You need to add spaces in the command string. Change it to
command = "nmap " + options + " " + ip
Related
I'm making a script that runs a command line and then shows the output in flask webpage.
The problem I'm facing is that the output is malformed, it looks like this.
img
here's my what I have wrote so far:
import subprocess as sp
#app.route('/harvester/scan',methods=['GET','POST'])
def harv():
domain=request.values.get('domain')
outputt=sp.getoutput("theharvester" + " " + "-d" + " " + domain + " " + "-l 10 -b all" )
return outputt
Function subprocess.getoutput is a legacy one. Try using subprocess.run instead.
Here is the example:
import subprocess
command = 'printf "1\n2"'
out = subprocess.run(command, capture_output=True).stdout.decode()
When i run below code i see the process terminates even before completion.
I validated command by running it manually command just works file.
cmssso-util produces output which are about 1200 lines.Can this be a buffer issue.
I validated script by assigning 'ls -ltr' to variable command works fine.
Referred Documentation from below link:
https://pexpect.readthedocs.io/en/stable/_modules/pexpect/run.html
I tried prefixing command by 'bash -c' which did not fix this issue.
I tried to find out how pexpect determines to terminate a process , still could not get any clear documentation.
Please help me.
import pexpect
command = "cmsso-util domain-repoint -m execute --src-emb-admin " + 'sourceVcAdmin' + " --replication-partner-fqdn " + 'destVc' + " --replication-partner-admin " + 'destVcAdmin' + " --dest-domain-name " + 'destDomain'
print("Running command : " + command)
(command_output, exitstatus) = pexpect.run(command ,withexitstatus=1, events={'Enter Source embedded vCenter Server Admin Password :' : '\r\n','Enter Replication partner Platform Services Controller Admin Password :' : '\r\n','All Repoint configuration settings are correct; proceed?(.*)' : 'Y\r\n'})
print("----Command output------------")
print(command_output)
print("-----------------------------")
assert exitstatus is 0 , "Execution Failed"
print("Successfully Completed Embedded Cross Domain Re-pointing ")
I could resolve this issue by using the following code:
import pexpect
try :
command = "cmsso-util domain-repoint -m execute --src-emb-admin " + 'sourceVcAdmin' + " --replication-partner-fqdn " + 'destVc' + " --replication-partner-admin " + 'destVcAdmin' + " --dest-domain-name " + 'destDomain'
print("Running command : " + command)
child = pexpect.spawn(command, timeout=3000,maxread=12000)
child.expect (['Enter Source embedded vCenter Server Admin Password :'],timeout=40000)
child.sendline(<password>)
child.expect (['Enter Replication partner Platform Services Controller Admin Password :'],timeout=40000)
child.sendline(<password>)
child.expect (['All Repoint configuration settings are correct; proceed?(.*)'],timeout=40000)
child.sendline('Y')
child.expect(pexpect.EOF)
print(child.before)
assert(child.status == 0 , "Operation Failed!", "Successfully Completed Embedded Cross Domain Re-pointing")
except:
print("Exception was thrown")
print("debug information:")
print(str(child))
child.close()
exit(1)
This is done by increasing default child = pexpect.spawn(command, timeout=600,maxread=8000)value and maxread parameters
I am attempting to use paramiko to send powershell commands over ssh to a Windows box with OpenSSH on it. The commands appear to be successful (return code 0) even when they should fail, and I'm not getting any output on the pipes. When I try commands like making a directory, it is not created, which makes it seem as though the commands aren't reaching the remote system, but also aren't throwing errors.
First, here's my code:
version = self.oscall.run_remote(['java', '-version'])
def run_remote(self, command): # Command is a list of command + args
string = ""
self.timeout = 300
for arg in command:
string = string + " " + arg
self.client.connect(self.host, username=self.user, password=self.pw, timeout=self.timeout)
self.transport = self.client.get_transport()
self.transport.set_keepalive(1)
self.channel = self.transport.open_session(timeout=self.timeout) # transport is abstract connection, session is socket
if self.channel.gettimeout() == None: self.channel.settimeout(self.timeout)
self.channel.exec_command(string)
self.out = self.channel.makefile()
self.err = self.channel.makefile_stderr()
self.output = CallOutput(self.out, self.err, None)
self.output.returncode = self.channel.recv_exit_status()
self.channel.close()
return self.output
class CallOutput(object):
def __init__(self, out, err, rc):
self.out = out.readlines()
self.err = err.readlines()
self.outfile = tempfile.TemporaryFile()
for line in self.out:
if isinstance(line, unicode): line = line.encode('utf-8')
self.outfile.write(line + '\n')
self.outfile.seek(0)
self.errfile = tempfile.TemporaryFile()
for line in self.err:
if isinstance(line, unicode): line = line.encode('utf-8')
self.errfile.write(line + '\n')
self.errfile.seek(0)
self.returncode = rc
Sorry for the wall of text, but I went for completeness. This is part of a larger application.
This code works perfectly connecting to Linux, so I don't expect there to be many little bugs. The returncode is always 0, even for garbage, and there is never any output on the pipes. If I run the command just using the terminal, I get the correct output:
$ ssh testuser#testwin.internal.com 'java -version'
Warning: Permanently added 'testwin.internal.com,10.10.10.12' (ECDSA) to the
list of known hosts.
testuser#testwin.internal.com's password:
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
$ echo $?
0
$ ssh testuser#testwin.internal.com 'foo'
foo : The term 'foo' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path
is correct and try again.
At line:1 char:1
+ foo
+ ~~~
+ CategoryInfo : ObjectNotFound: (foo:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
$ echo $?
1
The only difference between our Linux and Windows processes that I can think of is that on Windows we have to use a password, as we haven't setup passwordless ssh yet. What weird Windows idiosyncrasy am I missing? Any insights would be greatly appreciated.
As usual, it turns out to be way simpler than I was thinking.
string = ""
for arg in command:
string = string + " " + arg
The above code produces " whatever command was passed in" and it turns out that Windows reacts extremely poorly to the preceding space, while linux didn't care. The new code snippet is:
string = ""
first = True
for arg in command:
if first:
string = string + arg
first = False
else:
string = string + " " + arg
I'm leaving the title and details the same, to hopefully help anyone who makes the exact same error I did.
Has anyone been successful in doing this on windows? I'm trying to command a DSLR camera to take photos with Python over USB on a Windows machine. Or do you have a better solution (I am unable to switch to Linux).
Here's a working solution, using Python 3.5 (installed via Anaconda), BTW.
The parameters for the ISO and shutter are hardwired, but this should get you going if you ever need it.
import sys
import os
import subprocess
import datetime
def func_TakeNikonPicture(input_filename):
camera_command = 'C:\Program Files (x86)\digiCamControl\CameraControlCmd.exe'
camera_command_details = '/filename ./' + input_filename + ' /capture /iso 500 /shutter 1/30 /aperture 1.8'
print('camera details = ',camera_command_details)
full_command=camera_command + ' ' + camera_command_details
p = subprocess.Popen(full_command, stdout=subprocess.PIPE, universal_newlines=True, shell=False)
(output, err) = p.communicate()
#This makes the wait possible
p_status = p.wait(1)
# print(p.stdout.readline())
#This will give you the output of the command being executed
print('Command output: ' + str(output))
print('Command err: ' + str(err))
print('done')
if(len(sys.argv) < 2):
rawimagename = 'test.jpg'
else:
# sys.argv[0] is the program name, sys.argv[1] is the first file, etc.
# need to shift this over
files = sys.argv[1:len(sys.argv)]
# Read the image
rawimagename = files[0]
if(os.path.isfile(rawimagename) is True):
print("File exists...not overwriting.")
sys.exit()
# Store date/time for file uniqueness
current_dt=datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
print("Current date time = " + current_dt)
rawimagename=current_dt + '_' + rawimagename
print('Name of raw image will be: ', rawimagename)
# take picture
func_TakeNikonPicture(rawimagename)
Digicamcontrol have a remote utility which can control the application almost all aspects, the utility can be run in command prompt or execute using subprocess.call in Python
For more info about utility command line arguments check this link http://digicamcontrol.com/doc/userguide/remoteutil
I'm trying to use a PHP file on a server to transmit some variables into a Python script which will in turn start a raspistill timelapse on my Raspberry Pi.
I've so far managed to start taking pictures but I'd now like to have a button to kill the timelapse - i've tried many methods including .kill() and .terminate() but cant get it working.
Here is my current python code:
import sys, os, time, datetime
import subprocess
import signal
from time import sleep
tlfreq = int(sys.argv[1])
tltime = int(sys.argv[2])
dir = '/var/www/timelapse/' + sys.argv[3]
if not os.path.exists(dir):
os.makedirs(dir)
cmd = ('raspistill -t ' + str(tltime) + " -tl " + str(tlfreq) + " -o " + dir + "/photo_%04d.jpg")
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,
shell=True, preexec_fn=os.setsid)
print "Pictures are now being taken every" , tlfreq/1000 , "second/s for a total of", tltime/3600000 , "hours. These are being stored in", dir
Perhaps I need an "if variable = 1 then kill" command and then send the variable to python.
Any help would be greatly appreciated!
Many thanks,
Dan
You can create new python script kill_raspystill.py with this code
import os
os.system("pkill raspistill")
and call that script when you press a button.
I would suggest the signal library: http://docs.python.org/2/library/signal.html