[英]Python error: command not found
我最近買了一本書,開始用python玩,下面是其中一個腳本:
#!/usr/bin/python2.7
import sys
import socket
import getopt
import threading
import subprocess
# define some global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
# this runs a command and returns the output
def run_command(command):
# trim the newline
command = command.rstrip()
# run the command and get the output back
try:
output = subprocess.check_output(command,stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command.\r\n"
# send the output back to the client
return output
# this handles incoming client connections
def client_handler(client_socket):
global upload
global execute
global command
# check for upload
if len(upload_destination):
# read in all of the bytes and write to our destination
file_buffer = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination,"wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
# acknowledge that we wrote the file out
client_socket.send("Successfully saved file to %s\r\n" % upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" % upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# we have a valid command so execute it and send back the results
response = run_command(cmd_buffer)
# send back the response
client_socket.send(response)
# this is for incoming connections
def server_loop():
global target
global port
# if no target is defined we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target,port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler,args=(client_socket,))
client_thread.start()
# if we don't listen we are a client....make it so.
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target,port))
# if we detect input from stdin send it
# if not we are going to wait for the user to punch some in
if len(buffer):
client.send(buffer)
while True:
# now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response+= data
if recv_len < 4096:
break
print response,
# wait for more input
buffer = raw_input("")
buffer += "\n"
# send it off
client.send(buffer)
except:
# just catch generic errors - you can do your homework to beef this up
print "[*] Exception! Exiting."
# teardown the connection
client.close()
def usage():
print "Netcat Replacement"
print
print "Usage: bhpnet.py -t target_host -p port"
print "-l --listen - listen on [host]:[port] for incoming connections"
print "-e --execute=file_to_run - execute the given file upon receiving a connection"
print "-c --command - initialize a command shell"
print "-u --upload=destination - upon receiving connection upload a file and write to [destination]"
print
print
print "Examples: "
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -c"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./bhpnet.py -t 192.168.11.12 -p 135"
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-l","--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False,"Unhandled Option"
# are we going to listen or just send data from stdin
if not listen and len(target) and port > 0:
# read in the buffer from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
buffer = sys.stdin.read()
# send data off
client_sender(buffer)
# we are going to listen and potentially
# upload things, execute commands and drop a shell back
# depending on our command line options above
if listen:
server_loop()
main()
我已經調試了腳本並嘗試在終端中運行它,但是它似乎掛了一段時間,然后出現以下錯誤:
./bhnet.py: line 10: listen: command not found
./bhnet.py: line 11: =: command not found
./bhnet.py: line 12: upload: command not found
./bhnet.py: line 13: execute: command not found
./bhnet.py: line 14: target: command not found
./bhnet.py: line 15: upload_destination: command not found
./bhnet.py: line 16: port: command not found
./bhnet.py: line 19: syntax error near unexpected token `('
./bhnet.py: line 19: `def run_command(command):'
我將代碼與書中的代碼一並檢查,甚至沒有實際的代碼,因此我也嘗試過,但仍然一無所獲。 我希望我能比這更具體。 任何建議,將不勝感激。 謝謝。
這並不是我真正的專長,但是我會盡力闡明一下。
背景資料
在類似Unix的系統中運行腳本時,通常可以調用解釋器程序,並將腳本路徑作為參數傳遞,例如python bhnet.py
。
但是,如果您進行了適當的配置,則還可以將腳本作為獨立的可執行文件運行: ./bhnet.py
。 為此,通常需要:
確保執行權限已打開( chmod +x
或同等權限)。
在腳本的第一行以符號#!
(稱為“ shebang”),然后是要使用的解釋器的路徑。
你的情況
文件的第一行是#!/usr/bin/python2.7
,這似乎很合理。 運行./bhnet.py
時應該發生的是/usr/bin/python2.7
中的解釋器應該習慣於運行腳本。 只要/usr/bin/python2.7
是Python解釋器,就可以了...
但是,似乎正在發生的事情是,當您運行./bhnet.py
時,正在調用的解釋器都試圖將腳本作為shell腳本而不是Python來運行。 出於某種原因,也許/usr/bin/python2.7
路徑中實際上沒有的內容都不是Python。 或者,您的文件實際上並不是從您在問題中粘貼的內容開始的,但是您可能不小心用了一個不同的解釋器指令覆蓋了文件的第一行,例如#!/bin/sh
? 可能還有其他原因也可能導致此。
無論如何,默認的python
似乎工作正常。 (要查看您的默認設置指向什么,可以運行which python
。)
建議
如果要將文件作為獨立的可執行文件(即./bhnet.py
)運行,請嘗試將第一行更改為:
#!/usr/bin/env python
這似乎是Python推薦的shebang行,在您的情況下應該可以正常工作。 但是我仍然想知道您的/usr/bin/python2.7
發生了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.