Ubuntu子系统shell脚本自动连接xfce4界面

脚本功能

  • 命令行参数指定ip连接/获取ifconfig中的本地ip连接
  • 修改.bashrc
#!/bin/bash

net_dev="wifi0" #默认的设备名
FALSE="0"
TRUE="1"

# 若无参数则选择本地ipv4 通过正则匹配ifconfig $net_dev的内容
l_ip=$(ifconfig $net_dev | grep "inet" | grep -v "inet6" |
        sed 's/^.*inet//g' | sed 's/netmask.*$//g' | sed 's/ //g')
ok_ip=$l_ip
is_ok=$FALSE

m_ip=$1 #命令行指定参数获取
if [ "$m_ip" = "" ];then
        is_ip=$(echo $l_ip | grep -P "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
        if [ "$is_ip" = "" ];then
                echo "ip is wrong or not found"
        else
                echo "use local ip"
                is_ok=$TRUE
        fi
else
        is_ip=$(echo $m_ip | grep -P "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
        if [ "$is_ip" = "" ];then
                echo "inputed ip is wrong ,you can retry or using default ip"
        else
                echo "use inputed ip"
                is_ok=$TRUE
                ok_ip=$is_ip
        fi
fi

if [ "$is_ok" = "1" ];then
        echo "Waiting for xfce connected to $ok_ip open"
        sed -i "$ s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/$ok_ip/" ./.bashrc
        source ./.bashrc
        startxfce4
fi

注意事项

  • 脚本修改的是.bashrc最后一行中的ip
export DISPLAY=192.168.x.x:0
  • 因为脚本中有source命令,所以在终端中执行命令时要加source
# 本地ipv4执行
source ./openxfce4.sh

# 指定ip执行
source ./openxfce4.sh ip_addr
  • 执行脚本前先启动xfce4

补充

  • 因为想学习linux内核驱动,又不想放弃子系统,所以把wsl1升到wsl2了,然后悲剧了,没wifi0

The network interface you see in WSL isn't the host machine's network interface directly; what WSL sees is a virtual network interface (for the light VM WSL2 runs within) connected to a Hyper-V virtual switch behind the host's network card, so all WSL's network tools see is that virtual interface, as eth0.

  • 本来以为脚本改下设备名就行,可是没用,目前限于技术水平,只能在windows环境下ipconfig获取WLANIP,然后脚本执行时加上就行。
posted @ 2022-11-26 19:41  pie_thn  阅读(43)  评论(0编辑  收藏  举报