Friday, December 21, 2012

Fedora 17: Open port for TCP connection

To open a port for TCP connection you have to edit /etc/sysconfig/iptables and append the following line before the COMMIT line

-A INPUT -m state --state NEW -m tcp -p tcp --dport <PORT> -j ACCEPT

And then restart the iptables service by executing

service iptables restart

*EDIT*
I created this post before knowing that you could actually use iptables directly as below :P :

# iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport <PORT> -j ACCEPT

You should list your iptables rules first to check whether there's any DROP rule. If your new rule comes after a rule that DROPs any connection on you target port, the port you're trying to open will stay closed. If there's a DROP rule, use -I (insert) instead:

# iptables -I INPUT <rulenum> -m state --state NEW -m tcp -p tcp --dport <PORT> -j ACCEPT

where <rulenum> is the rule index in the chain. and <PORT> is your target port.

Friday, December 14, 2012

Python: Fun with sockets (remote desktop)

Server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#!/usr/bin/python

import os
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)

client, addr = s.accept()

cmd = s.recv(1024)
try:
    os.system(cmd)
    client.sendall("OK")
except:
    client.sendall("FAIL")
client.close()

Client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(sys.argv[1])

data = s.recv(32)

print data
s.close()
print "Received: '%s'"%data