夜火博客

Perl版NetCat(NC)

2008-11-04
技术文章
Perl
技术类
3分钟
527字

这个机器有多古老?4.6-RELEASE FreeBSD,没有gcc,没有make,连系统都乱七八糟的,port都不好使,pkg_add -r安装包都会有问题,真是无语了,还好有安装了一个Perl 5.8.8。修理Port花了半天时间,硬是没搞好。想想也不划算,把紧急要用的一些小工具花一会儿功夫自己做一个出来算了,于是有了这个简单的Perl 版NC,不过我没支持-e参数,用不着。

1
1. #!/usr/bin/perl
2
3. use strict;
3
4. use IO::Socket;
4
5. use IO::Select;
5
6. use Getopt::Std;
6
8. my %option;
7
9. getopts('lp:', %option);
8
11. # listen on local port
9
12. if( defined $option{'l'} )
10
13. {
11
14. if( !defined $option{'p'} )
12
15. {
13
16. &Usage( );
14
17. exit( -1 );
15
18. }
87 collapsed lines
16
20. my $port = $option{'p'};
17
21. my $listen = IO::Socket::INET->new(Proto => 'tcp',
18
22. LocalPort => $port,
19
23. Listen => 1,
20
24. Reuse => 1) or die "Listen on port $port error: $!n";
21
26. while( my $client_sock = $listen->accept() )
22
27. {
23
28. &ProcessData( $client_sock );
24
29. }
25
30. }
26
32. # if has no -l argument, maybe want to connect to other host
27
33. if( @ARGV != 2 )
28
34. {
29
35. &Usage( );
30
36. exit( -1 );
31
37. }
32
39. my $client_sock = IO::Socket::INET->new(Proto => 'tcp', PeerHost => $ARGV[0], PeerPort => $ARGV[1] ) || die "Connect to $ARGV[0]:$ARGV[1] error:$!n";
33
40. &ProcessData( $client_sock );
34
42. sub ProcessData
35
43. {
36
44. my $client_sock = shift;
37
46. my $select = IO::Select->new( );
38
48. $select->add( *STDIN );
39
49. $select->add( $client_sock );
40
51. my $buffer;
41
52. while( 1 )
42
53. {
43
54. if( ! $select->exists( $client_sock ) )
44
55. {
45
56. print "waiting connection....n";
46
57. last;
47
58. }
48
60. my @ready = $select->can_read;
49
62. for my $tmp_sock(@ready)
50
63. {
51
64. if( $tmp_sock eq *STDIN )
52
65. {
53
66. if( my $recv_len = sysread( *STDIN, $buffer, 1024 )  )
54
67. {
55
68. if( ! syswrite($client_sock, $buffer) )
56
69. {
57
70. $select->remove( $client_sock );
58
71. $select->remove( *STDIN );
59
72. close( $client_sock );
60
74. last;
61
75. }
62
76. }
63
77. else
64
78. {
65
79. $select->remove( $client_sock );
66
80. $select->remove( *STDIN );
67
81. close( $client_sock );
68
83. last;
69
84. }
70
85. }
71
87. elsif( $tmp_sock eq $client_sock )
72
88. {
73
89. if( my $recv_len = sysread( $client_sock, $buffer, 1024*5 ) )
74
90. {
75
91. if( ! syswrite( *STDOUT, $buffer) )
76
92. {
77
93. $select->remove( $client_sock );
78
94. $select->remove( *STDIN );
79
95. close( $client_sock );
80
97. last;
81
98. }
82
99. }
83
100. else
84
101. {
85
102. print "socket disconnected.n";
86
103. $select->remove( $client_sock );
87
104. $select->remove( *STDIN );
88
105. close( $client_sock );
89
107. last;
90
108. }
91
109. }
92
110. }
93
111. }
94
112. }
95
114. sub Usage
96
115. {
97
116. print "simple nc.pl, code by wustyunshu@hotmail.comn";
98
117. print "this script don't support -e cmd.exe, ^_^n";
99
118. print "Usage:n";
100
119. print "t  -l -p 99n";
101
120. print "t 192.168.0.1 80n";
102
121. }

Author:云舒

本文标题:Perl版NetCat(NC)
文章作者:夜火
发布时间:2008-11-04