質問するログイン新規登録

質問編集履歴

4

教えていただいた箇所の修正後、一つだけエラーが出たので更新

2020/08/01 04:26

投稿

t4gforce
t4gforce

スコア5

title CHANGED
File without changes
body CHANGED
@@ -4,30 +4,10 @@
4
4
 
5
5
  ### 発生している問題・エラーメッセージ
6
6
 
7
- エラーメッセージを全文記載いたします。
8
- サーバ側のTracebackは
9
7
  ```
10
- Exception in thread Thread-1:
11
- Traceback (most recent call last):
12
- File "C:\Users\--\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
13
- self.run()
14
- File "C:\Users\--\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
15
- self._target(*self._args, **self._kwargs)
16
- File "./bhnet.py", line 78, in client_handler
8
+ 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
17
- cmd_buffer += client_socket.recv(1024).decode() # サーバ側例外発生箇所
18
- TypeError: can't concat str to bytes
19
9
  ```
20
10
 
21
- クライアント側のTracebackは
22
- ```
23
- Traceback (most recent call last):
24
- File "./bhnet.py", line 122, in client_sender
25
- data = client.recv(4096).decode()
26
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
27
- ```
28
-
29
-
30
-
31
11
  ### 該当のソースコード
32
12
 
33
13
 
@@ -37,6 +17,11 @@
37
17
  一つのファイルの実行時に指定されたオプションで、サーバ側とクライアント側の動作が変わる様になっています。
38
18
  サーバとして動作させる場合は、python ./bhnet.py -l -p 9999 -c とオプションを指定し、
39
19
  そのサーバに接続する際は、python ./bhnet.py -t localhost -p 9999 とオプションを指定して起動しています。
20
+
21
+
22
+ ・encoding='utf-8'を追加し、再度更新しました
23
+
24
+
40
25
  ```python
41
26
  # coding:utf-8
42
27
 
@@ -67,8 +52,12 @@
67
52
  try:
68
53
  output = subprocess.check_output(
69
54
  command, stderr=subprocess.STDOUT, shell=True)
55
+ output = output.decode(encoding="shift-jis")
56
+ # output = output.decode(encoding="utf-8") # 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
70
- except Exception:
57
+ except Exception as e:
58
+ output = str(e)
59
+ output += "\r\n"
71
- output = "Failed to execute command.\r\n"
60
+ output += "Failed to execute command.\r\n"
72
61
 
73
62
  return output
74
63
 
@@ -84,7 +73,7 @@
84
73
  file_buffer = ""
85
74
 
86
75
  while True:
87
- data = client_socket.recv(1024).decode()
76
+ data = client_socket.recv(1024).decode(encoding='utf-8')
88
77
 
89
78
  if not data:
90
79
  break
@@ -105,20 +94,20 @@
105
94
  # コマンドの実行(execute)が指定されたときの動作
106
95
  if len(execute):
107
96
  output = run_command(execute)
108
- client_socket.send(output)
97
+ client_socket.send(output.encode(encoding='utf-8'))
109
98
 
110
99
  # commandが指定された場合はシェルとして動作する
111
100
  if command:
112
101
  while True:
113
102
  propmt = "<BHP:#> "
114
- client_socket.send(propmt.encode())
103
+ client_socket.send(propmt.encode(encoding='utf-8'))
115
104
 
116
- cmd_buffer = b""
105
+ cmd_buffer = ""
117
- while b"\n" not in cmd_buffer:
106
+ while "\n" not in cmd_buffer:
118
- cmd_buffer += client_socket.recv(1024).decode() # サーバ側例外発生箇所
107
+ cmd_buffer += client_socket.recv(1024).decode(encoding='utf-8')
119
108
  response = run_command(cmd_buffer)
120
109
 
121
- client_socket.send(response)
110
+ client_socket.send(response.encode(encoding='utf-8'))
122
111
 
123
112
 
124
113
  # 受信用の関数
@@ -154,15 +143,14 @@
154
143
  print("connected!")
155
144
 
156
145
  if len(buffer):
157
- client.send(buffer.encode())
146
+ client.send(buffer.encode(encoding='utf-8'))
158
147
 
159
148
  while True:
160
149
  recv_len = 1
161
150
  response = ""
162
151
 
163
152
  while recv_len:
164
- # クライアント側例外発生箇所
165
- data = client.recv(4096).decode()
153
+ data = client.recv(4096).decode(encoding='utf-8')
166
154
  recv_len = len(data)
167
155
  response += data
168
156
 
@@ -174,7 +162,7 @@
174
162
  buffer = input("")
175
163
  buffer += "\n"
176
164
 
177
- client.send(buffer.encode(encoding="utf-8"))
165
+ client.send(buffer.encode(encoding='utf-8'))
178
166
  except Exception as e:
179
167
  print(e)
180
168
  print(traceback.format_exc())
@@ -238,6 +226,9 @@
238
226
  プログラムのコードすべてとTraceback全文を追記しました。
239
227
  長くなってしまいますが、よろしくお願いいたします。
240
228
 
229
+ 再度更新いたしました
230
+ 重ねてお願いとなってしまいますが、よろしくお願いいたします。
231
+
241
232
  ### 補足情報(FW/ツールのバージョンなど)
242
233
 
243
234
  Python 3.8.1

3

プログラムのコードすべてを追記、Traceback全文を追記

2020/08/01 04:25

投稿

t4gforce
t4gforce

スコア5

title CHANGED
File without changes
body CHANGED
@@ -13,9 +13,9 @@
13
13
  self.run()
14
14
  File "C:\Users\--\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
15
15
  self._target(*self._args, **self._kwargs)
16
- File "./bhnet.py", line 74, in client_handler
16
+ File "./bhnet.py", line 78, in client_handler
17
- cmd_buffer += client_socket.recv(1024).decode()
17
+ cmd_buffer += client_socket.recv(1024).decode() # サーバ側例外発生箇所
18
- ConnectionResetError: [WinError 10054] 既存の接続はリモート ホストに強制的に切断されました。
18
+ TypeError: can't concat str to bytes
19
19
  ```
20
20
 
21
21
  クライアント側のTracebackは
@@ -113,8 +113,8 @@
113
113
  propmt = "<BHP:#> "
114
114
  client_socket.send(propmt.encode())
115
115
 
116
- cmd_buffer = ""
116
+ cmd_buffer = b""
117
- while "\n" not in cmd_buffer:
117
+ while b"\n" not in cmd_buffer:
118
118
  cmd_buffer += client_socket.recv(1024).decode() # サーバ側例外発生箇所
119
119
  response = run_command(cmd_buffer)
120
120
 

2

プログラムのコードすべてを追記、Traceback全文を追記

2020/07/30 15:24

投稿

t4gforce
t4gforce

スコア5

title CHANGED
File without changes
body CHANGED
@@ -4,44 +4,240 @@
4
4
 
5
5
  ### 発生している問題・エラーメッセージ
6
6
 
7
- 例外が発生します。
7
+ エラーメッセージを全文記載いたします。
8
+ サーバ側のTracebackは
8
9
  ```
10
+ Exception in thread Thread-1:
11
+ Traceback (most recent call last):
12
+ File "C:\Users\--\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
13
+ self.run()
14
+ File "C:\Users\--\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
15
+ self._target(*self._args, **self._kwargs)
9
- 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
16
+ File "./bhnet.py", line 74, in client_handler
17
+ cmd_buffer += client_socket.recv(1024).decode()
18
+ ConnectionResetError: [WinError 10054] 既存の接続はリモート ホストに強制的に切断されました。
10
19
  ```
11
20
 
21
+ クライアント側のTracebackは
22
+ ```
23
+ Traceback (most recent call last):
24
+ File "./bhnet.py", line 122, in client_sender
25
+ data = client.recv(4096).decode()
26
+ UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
27
+ ```
28
+
29
+
30
+
12
31
  ### 該当のソースコード
13
32
 
33
+
34
+ エラーが起きているソースコードを追記させていただきます。
35
+ 以下のリンクのコードを参考にしています。
36
+ https://github.com/AllGloryToTheHypnotoad/Black-Hat-Python/blob/master/BHP-Code/Chapter2/bhnet.py
37
+ 一つのファイルの実行時に指定されたオプションで、サーバ側とクライアント側の動作が変わる様になっています。
38
+ サーバとして動作させる場合は、python ./bhnet.py -l -p 9999 -c とオプションを指定し、
39
+ そのサーバに接続する際は、python ./bhnet.py -t localhost -p 9999 とオプションを指定して起動しています。
14
40
  ```python
15
- client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
41
+ # coding:utf-8
16
42
 
17
- try:
18
- client.connect((localhost, 9999)) # 別途、localhost:9999でserver.listen()をしています。
43
+ # filename : bhnet.py
19
44
 
45
+ import sys
46
+ import socket
20
- buffer = input("")
47
+ import getopt
48
+ import threading
21
- buffer += "\n"
49
+ import subprocess
22
50
 
23
- print(type(buffer)) # <class 'str'>
51
+ import traceback
24
52
 
53
+ # global
54
+ listen = False
55
+ command = False
56
+ upload = ""
57
+ execute = ""
58
+ target = ""
25
- client.send(buffer.encode(encoding="utf-8")) # 例外発生
59
+ upload_destination = ""
60
+ port = 0
26
61
 
27
- except Exception as e:
28
- print(e) # 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
29
- client.close()
30
62
 
31
- ```
63
+ # コマンドを実行し出力を返す
64
+ def run_command(command):
65
+ command = command.rstrip()
32
66
 
67
+ try:
68
+ output = subprocess.check_output(
69
+ command, stderr=subprocess.STDOUT, shell=True)
33
- ### 試したこと
70
+ except Exception:
71
+ output = "Failed to execute command.\r\n"
34
72
 
73
+ return output
74
+
75
+
76
+ # クライアントが送ったデータを処理する
77
+ def client_handler(client_socket):
78
+ global upload
79
+ global execute
80
+ global command
81
+
82
+ # uploadが指定されたときの動作
83
+ if len(upload_destination):
84
+ file_buffer = ""
85
+
86
+ while True:
87
+ data = client_socket.recv(1024).decode()
88
+
89
+ if not data:
90
+ break
91
+ else:
92
+ file_buffer += data
93
+
94
+ try:
95
+ file_descriptor = open(upload_destination, "wb")
96
+ file_descriptor.write(file_buffer)
97
+ file_descriptor.close()
98
+
99
+ client_socket.send(
100
+ b"Successfully saved file to %s\r\n" % upload_destination)
101
+ except Exception:
102
+ client_socket.send(
103
+ b"Failed saved file to %s\r\n" % upload_destination)
104
+
105
+ # コマンドの実行(execute)が指定されたときの動作
35
- 例外発生箇所のコードを書き換え、
106
+ if len(execute):
107
+ output = run_command(execute)
108
+ client_socket.send(output)
109
+
110
+ # commandが指定された場合はシェルとして動作する
111
+ if command:
112
+ while True:
113
+ propmt = "<BHP:#> "
114
+ client_socket.send(propmt.encode())
115
+
116
+ cmd_buffer = ""
117
+ while "\n" not in cmd_buffer:
118
+ cmd_buffer += client_socket.recv(1024).decode() # サーバ側例外発生箇所
119
+ response = run_command(cmd_buffer)
120
+
121
+ client_socket.send(response)
122
+
123
+
124
+ # 受信用の関数
125
+ def server_loop():
126
+ global target
127
+ global port
128
+
129
+ # ターゲットの指定がなければすべてのアクセスを受け付ける
130
+ if not len(target):
131
+ target = "0.0.0.0"
132
+
133
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
134
+ server.bind((target, port))
135
+
136
+ server.listen(5)
137
+
138
+ while True:
139
+ client_socket, addr = server.accept()
140
+
141
+ # クライアントの処理を行うスレッドの作成
142
+ client_thread = threading.Thread(
143
+ target=client_handler, args=(client_socket,))
144
+ client_thread.start()
145
+
146
+
147
+ # クライアントとしてデータを送信する関数
148
+ def client_sender(buffer):
149
+
150
+ client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
151
+
152
+ try:
153
+ client.connect((target, port))
154
+ print("connected!")
155
+
156
+ if len(buffer):
157
+ client.send(buffer.encode())
158
+
159
+ while True:
160
+ recv_len = 1
161
+ response = ""
162
+
163
+ while recv_len:
164
+ # クライアント側例外発生箇所
165
+ data = client.recv(4096).decode()
166
+ recv_len = len(data)
167
+ response += data
168
+
169
+ if recv_len < 4096:
170
+ break
171
+
172
+ print(response)
173
+
174
+ buffer = input("")
175
+ buffer += "\n"
176
+
177
+ client.send(buffer.encode(encoding="utf-8"))
178
+ except Exception as e:
36
- ```python
179
+ print(e)
180
+ print(traceback.format_exc())
181
+ print("[*] Exception! Exiting.")
182
+ client.close()
183
+
184
+
185
+ def main():
186
+ global listen
187
+ global port
188
+ global execute
189
+ global command
190
+ global upload_destination
191
+ global target
192
+
193
+ if not len(sys.argv[1:]):
194
+ sys.exit(0)
195
+
196
+ try:
197
+ opts, args = getopt.getopt(
198
+ sys.argv[1:],
199
+ "hle:t:p:cu",
200
+ ["help", "listen", "execute=", "target=",
201
+ "port=", "command", "upload="]
202
+ )
203
+ except getopt.GetoptError as err:
204
+ print(str(err))
205
+ for o, a in opts:
206
+ if o in ("-l", "--listen"):
207
+ listen = True
208
+ elif o in ("-e", "--execute"):
209
+ execute = a
210
+ elif o in ("-c", "--commandshell"):
211
+ command = True
212
+ elif o in ("-u", "--upload"):
213
+ upload_destination = a
214
+ elif o in ("-t", "--target"):
215
+ target = a
216
+ elif o in ("-p", "--port"):
217
+ port = int(a)
218
+ else:
219
+ assert False, "Unhandled Option"
220
+
221
+ # クライアントとして動作
222
+ if not listen and len(target) and port > 0:
223
+ buffer = sys.stdin.read()
37
- client.send(bytes(buffer))
224
+ client_sender(buffer)
225
+
226
+ # サーバとして動作
227
+ if listen:
228
+ print("...")
229
+ server_loop()
230
+
231
+
232
+ main()
38
233
  ```
39
- を試しましたが、string argument without an encoding という例外が発生してしまいます。
40
234
 
41
235
 
42
- python3でsendする方法を教えていただきたいです。
43
- よろくお願いします。
236
+ ### 試たこと
44
237
 
238
+ プログラムのコードすべてとTraceback全文を追記しました。
239
+ 長くなってしまいますが、よろしくお願いいたします。
240
+
45
241
  ### 補足情報(FW/ツールのバージョンなど)
46
242
 
47
243
  Python 3.8.1

1

例外メッセージの追加

2020/07/30 15:06

投稿

t4gforce
t4gforce

スコア5

title CHANGED
File without changes
body CHANGED
@@ -25,7 +25,7 @@
25
25
  client.send(buffer.encode(encoding="utf-8")) # 例外発生
26
26
 
27
27
  except Exception as e:
28
- print(e)
28
+ print(e) # 'utf-8' codec can't decode byte 0x83 in position 1: invalid start byte
29
29
  client.close()
30
30
 
31
31
  ```