? ? ? ?最近突然想到了一個可以繞開單位安全管控軟件,讓單位內部辦公電腦連上外網的方法。大概是這個樣子,讓單位辦公電腦與自己的外網電腦進行藍牙配對,然后用配對成功的藍牙進行網絡數據交互。這里大家可能會想用一下藍牙的網絡共享功能,分分鐘不就實現了,其實這里是有問題的,因為這樣會在單位內部辦公電腦上虛擬出一個網卡,馬上會被單位安全管控軟件識別,進而被網絡管理員發現,至少我們單位是這樣的,所以不能這樣用,我這里用Java寫了一個藍牙數據通訊的程序,同時考慮到藍牙數據通訊較慢,直接用瀏覽器訪問太慢,又用Python爬了幾個自己經常訪問的網站,用爬蟲只訪問有用信息,減少藍牙數據通訊的數據量,最后總體感覺相當不錯。下面以辦公電腦連接外網實現中英文翻譯為例進行介紹。拓撲圖如下:
藍牙數據交換功能用Java語言實現,其中用到了[bluecove-2.1.1.jar]藍牙功能操作包。客戶端安裝在內網電腦上(比如辦公電腦),在接收到內網電腦訪問外部網絡訪的Socket請求后,自動與外網電腦進行藍牙連接,并將Socket通訊數據轉為藍牙通訊數據,鏡像至外網,主要代碼如下:
public class SocketServer {private String bluetoothRemoteUrl = null;public SocketServer() {}public void start() throws IOException {try (ServerSocket server = new ServerSocket(SocketConfig.SERVER_PORT,SocketConfig.SERVER_BACKLOG,InetAddress.getByName(SocketConfig.SERVER_ADDRESS))) {System.out.print("Socket通訊監聽[" + SocketConfig.SERVER_ADDRESS + ":" + SocketConfig.SERVER_PORT + "]啟動成功...");ExecutorService service = Executors.newFixedThreadPool(BluetoothConfig.SERVICE_POOL);System.out.println("服務線程池[" + BluetoothConfig.SERVICE_POOL + "]初始化成功...");Socket socket = null;BluetoothChannel channel = null;while(true) {try {socket = server.accept();System.out.println("客戶端[" + socket.getInetAddress().getHostAddress() + "]已連接...");}catch(Exception e) {System.out.println("客戶端連接錯誤[" + e.getMessage() + "]");if (socket != null) {socket.close();}continue;}System.out.print("開始與藍牙服務[" + BluetoothConfig.REMOTE_UUID + "@" + BluetoothConfig.REMOTE_ADDRESS + "]建立連接...");try {if (StrUtil.isBlank(bluetoothRemoteUrl)) {bluetoothRemoteUrl = BluetoothTools.fetchRemoteUrl(BluetoothConfig.REMOTE_ADDRESS,new UUID(BluetoothConfig.REMOTE_UUID,true),ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);}channel = BluetoothTools.open(bluetoothRemoteUrl);System.out.println("已連接");}catch (Exception e) {System.out.println("連接錯誤[" + e.getMessage() + "]");if (socket != null) {socket.close();}if (channel != null) {channel.close();}continue;}service.execute(new SendService(socket,channel));service.execute(new RecvService(socket,channel));}}}
服務端安裝在外網電腦,在接收到客戶端藍牙連接請求后,自動與代理服務器(或目標網站)進行Socket連接,并重新將藍牙通訊數據轉為Socket通訊數據,發送至代理服務器(或目標網站),然后接收代理服務器(或目標網站)響應,鏡像至客戶端,主要服務端代碼如下:
public class BluetoothServer {public BluetoothServer() {}public void start() throws BluetoothStateException,IOException {LocalDevice bluetooth = LocalDevice.getLocalDevice();bluetooth.setDiscoverable(DiscoveryAgent.GIAC);StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:" + BluetoothTools.genUuid(BluetoothConfig.SERVICE_UUID, true)+ ";name=" + BluetoothConfig.SERVICE_NAME);System.out.print("藍牙[" + bluetooth.getFriendlyName() + "]"+ "通訊監聽[" + BluetoothConfig.SERVICE_UUID + "@" + bluetooth.getBluetoothAddress() + "]啟動成功...");ExecutorService service = Executors.newFixedThreadPool(BluetoothConfig.SERVICE_POOL);System.out.println("服務線程池[" + BluetoothConfig.SERVICE_POOL + "]初始化成功...");BluetoothChannel channel = null;RemoteDevice device = null;Socket socket = null;while(true) {try {channel = new BluetoothChannel(notifier.acceptAndOpen());device = RemoteDevice.getRemoteDevice(channel.getStreamConnection());System.out.println("客戶端藍牙[" + device.getFriendlyName(true) + "]"+ "[" + device.getBluetoothAddress() + "]已連接...");}catch (Exception e) {System.out.println("客戶端藍牙連接錯誤[" + e.getMessage() + "]");if (channel != null) {channel.close();}continue;}System.out.print("開始與目標服務器[" + SocketConfig.TARGET_ADDRESS + ":" + SocketConfig.TARGET_PORT + "]建立連接...");try {socket = new Socket();socket.connect(new InetSocketAddress(SocketConfig.TARGET_ADDRESS,SocketConfig.TARGET_PORT),SocketConfig.TARGET_COTIMEOUT);socket.setSoTimeout(SocketConfig.TARGET_SOTIMEOUT);System.out.println("已連接");}catch (Exception e) {System.out.println("連接錯誤[" + e.getMessage() + "]");if (socket != null) {socket.close();}if (channel != null) {channel.close();}continue;}service.execute(new SendService(socket,channel));service.execute(new RecvService(socket,channel));}}}
藍牙數據流處理主要代碼如下:
public class BluetoothChannel implements Closeable {private StreamConnection connection = null;private DataInputStream dInStrm = null;private DataOutputStream dOutStrm = null;private boolean closed = true;public BluetoothChannel(StreamConnection connection)throws IOException {this.connection = connection;this.dInStrm = connection.openDataInputStream();this.dOutStrm = connection.openDataOutputStream();this.closed = false;}public DataInputStream getDataInputStream() {return this.dInStrm;}public DataOutputStream getDataOutputStream() {return this.dOutStrm;}public boolean isClosed() {return this.closed;}@Overridepublic void close() throws IOException {dOutStrm.close();dInStrm.close();connection.close();closed = true;}}
數據接收主要代碼下:
public class RecvService implements Runnable {private Socket socket = null;private BluetoothChannel channel = null;public RecvService(Socket socket,BluetoothChannel channel) {this.socket = socket;this.channel = channel;}@Overridepublic void run() {try {InputStream in = channel.getDataInputStream();OutputStream out = new DataOutputStream(socket.getOutputStream());int len = 0;byte[] data = new byte[CommonConfig.STREAM_BUFFER];try {while((len = in.read(data,0,CommonConfig.STREAM_BUFFER)) != -1) {out.write(data,0,len);out.flush();}} catch (IOException e) {}if (!channel.isClosed()) {channel.close();}if (!socket.isClosed()) {socket.close();}}catch (Exception e) {System.out.println("數據通訊處理錯誤[" + e.getMessage() + "]");e.printStackTrace();}}}
數據發送主要代碼如下:
public class SendService implements Runnable {private Socket socket = null;private BluetoothChannel channel = null;public SendService(Socket socket,BluetoothChannel channel) {this.socket = socket;this.channel = channel;}@Overridepublic void run() {try {InputStream in = new DataInputStream(socket.getInputStream());OutputStream out = channel.getDataOutputStream();int len = 0;byte[] data = new byte[CommonConfig.STREAM_BUFFER];try {while ((len = in.read(data,0,CommonConfig.STREAM_BUFFER)) != -1) {out.write(data,0,len);out.flush();}}catch (IOException e) {}if (!socket.isClosed()) {socket.close();}if (!channel.isClosed()) {channel.close();}}catch (Exception e) {System.out.println("數據通訊處理錯誤[" + e.getMessage() + "]");e.printStackTrace();}}}
注:以上java程序只是實現通過藍牙通訊實現內外網數據的鏡像,沒有代理功能,所以如果要實現對外網網站的訪問還需要在外網電腦上安裝代理服務器(可以使用目前較為流行的開源代理服務器nginx)。
中英文翻譯應用為用Python寫的一段爬蟲程序,使用cmd命令行下打開(python lexi.py),自動識別中英文,輸入中文翻譯成英文,輸入英文翻譯成中文。主要用到了requests包。具體代碼如下:
# -*- coding:utf-8 -*-import json
import reimport requestsheaders = {'accept':'application/json, text/plain, */*','accept-encoding':'gzip, deflate, br, zstd','accept-language':'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6','connection':'keep-alive','cookie':'ABTEST=0|1746782609|v17; SUID=1551A20B3E50A20B00000000681DC991; wuid=1746782609372; SUV=1746782609241; SNUID=93D7248D8680B23602BCFFD687A0005C; translate.sess=4b4c4608-becd-44e0-987c-d4e520a81c55; SGINPUT_UPSCREEN=1746782613767; FQV=d0ca8207c4cbb93a9ca15fda8d652a86','host':'fanyi.sogou.com','origin':'http://fanyi.sogou.com','referer':'http://fanyi.sogou.com/text','sec-ch-ua':'"Chromium";v="136", "Microsoft Edge";v="136", "Not.A/Brand";v="99"','sec-ch-ua-mobile':'?0','sec-ch-ua-platform':'"Windows"','sec-fetch-dest':'empty','sec-fetch-mode':'cors','sec-fetch-site':'same-origin','content-type':'application/json; charset=utf-8','user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0'
}
pattern = re.compile(pattern = r'<script>window\.__INITIAL_STATE__=(?P<data>.*?);\(function\(\){.*?</script>',flags = re.S) #爬取翻譯數據正則
proxies = {'http': 'http://xx.xx.xx.xx:xxxx' #填寫安裝在內網的客戶端地址
}def http_get(keyword,trans_to):response = requests.get(url = f'http://fanyi.sogou.com/text?keyword={keyword}&transfrom=auto&transto={trans_to}&model=general',headers = headers,proxies = proxies)response.encoding = 'utf-8'text = Noneif (response.status_code == 200):text = response.textresponse.close()return textdef chinese_to_english(json):print('詞典釋義:')for mean in json['textTranslate']['translateData']['wordCard']['secondQuery']:print(f' {mean['k']:<20}{mean['v']}')print('\n翻譯結果:')print(f' {json['textTranslate']['translateData']['sentencesData']['data']['trans_result'][0]['trans_text']}')def english_to_chinese(json):print('讀音:')voices = json['voice']['from'].get('list')if (voices):for voice in voices:print(f' {voice['abbr']}[{voice['phonetic']}]',end='')print('\n詞典釋義:')for mean in json['textTranslate']['translateData']['wordCard']['usualDict']:print(f' {mean['pos']:<10}{mean['values'][0]}')print('\n翻譯結果:')print(f' {json['textTranslate']['translateData']['translate']['dit']}')def is_chinese_char(char):#根據Unicode編碼范圍,判斷是否是中文字符if (char >= '\u4e00' and char <= '\u9fff') \or (char >= '\u3400' and char <= '\u4dbf') \or (char >= '\u20000' and char <= '\u2a6df') \or (char >= '\u3000' and char <= '\u303f'):return Trueelse:return Falsedef is_chinese_str(str):#統計字符串中的中文字符數count = sum(1 for c in str if is_chinese_char(c))if (len(str) / 2 <= count): #中文字符數占主導認為是中文(中文字符超過一半)return Trueelse:return Falseif (__name__ == '__main__'):print('翻譯程序已啟動...按[.]或[。]退出...')while (True):keyword = input('>')if ('.' == keyword or '。' == keyword): #按下 . 或 。 退出應用exit(0)if (is_chinese_str(keyword)):#通過正則提取翻譯結果數據data = pattern.search(string = http_get(keyword = keyword, trans_to = 'en')).group('data')if (not data):print('響應數據異常')exit(10)chinese_to_english(json.loads(data))else:#通過正則提取翻譯結果數據data = pattern.search(string = http_get(keyword = keyword, trans_to = 'zh-CHS')).group('data')if (not data):print('響應數據異常')exit(10)english_to_chinese(json.loads(data))
整個程序效果如下: