虚拟机代理设置

发布时间 2023-04-23 21:01:52作者: jrchyang

1 场景

一些日常开发、调试工作一般在虚拟机中进行,如需从GitHub下载源码,会由于网络问题导致经常下载失败,一般可以通过配置ssh或直接下载zip代码包来解决。但对于一些较大型的项目,会包含一些子模块并需要安装很多其他依赖项,如继续使用上述方式将导致将导致整个过程非常繁琐且不一定能够解决,可以通过终端配置代理的方式来解决,具体方法如下文。

2 配置代理

2.1 查看宿主机IP

# 在windows平台下,通过 ipconfig 命令查看
ipconfig

2.2 查看代理软件端口

这里直接查看自己使用的代理软件即可,以ss为例,端口为 1080 。另外,要勾选 允许其他设备连入 选项。

2.3 虚拟机配置

# 编辑 ~/bashrc 为本用户配置
vim ~/.bashrc

# 插入以下内容
# IP为宿主机IP
export https_proxy=http://$ip:1080
export http_proxy=http://$ip:1080
export all_proxy=socks5://$ip:1080

# 编辑完成后重新登录终端
# 如需取消代理则删除上述内容再重新登录

2.4 脚本自动化

每次编辑文件比较繁琐,我们可以将上述步骤添加到脚本中,从过脚本自动设置,如下:

#!/bin/bash

function add_proxy()
{
	if [ -z "$ip" ];then
		echo "please input ip address"
		exit
	fi

	cat >> ~/.bashrc <<EOF
export https_proxy=http://$ip:1080
export http_proxy=http://$ip:1080
export all_proxy=socks5://$ip:1080
EOF
}

function del_proxy()
{
	sed -i '/proxy/d' ~/.bashrc
}

function chk_proxy()
{
	cat ~/.bashrc | grep proxy
}

opt=$1
ip=$2

if [ "$opt" == "add" ];then
	add_proxy
elif [ "$opt" == "del" ];then
	del_proxy
elif [ "$opt" == "chk" ];then
	chk_proxy
else
	echo "invalid opt $opt"
fi