Android with root Git for version control Lircd with Raspberry Pi for IR receiver and sender Tips for Windows Depolying your own password management tool -- KeeWeb Depoly your flask app into Heroku Fix shit IE code manually ISBN to Book Category by Scraping DangDang A Generic Makefile for C/C++ Program Configure Raspberry pi Remove watermark with PyPDF2 tips for docker Anaconda+TensorFlow+CUDA Snippets Configure Remote Mathematica Kernel Build your own ngrok server Access Array SSL VPN 使用Rstudio制作html5幻灯片 tips for Mac OS X system Tips for ipython notebook 配置Ubuntu server + Openbox (Obuntu) tips for Vimperator tips for Vim 安装CUDA My First Jekyll Blog rsync常见选项 在Linux中读取Ipod touch的文件 tip for texmacs 在VPS上建站的一些tip Gnuplot绘图札记 Samba系统和autofs自动挂载 Linux中alsamixer声卡无法录音 搭建自己的RSS订阅器——Tiny Tiny RSS Grub2引导安装Ubuntu awk tips 将Ubuntu系统装入U盘 The Great Rtorrent 编译GCC 再这样剁手!!!该死的libgd 使用ulimit进行资源限制 使用SSH代理上IPV6 使用RCurl抓取网页数据 修复Ubuntu Grub记 openbox中的文件关联 在Ubuntu 12.04下编译qtiplot 处理BCM4312网卡驱动纪实 配置我的Ubuntu Server记 Cygwin杂记 Linux 使普通用户具有以超级权限执行脚本 让firefox自定义地处理文件类型 WordPress优秀主题及插件 在phpcloud上搭建wordpress UBUNTU下用pptpd做VPN server ubuntu升级内核过后的一些问题 安装telnet服务 kubuntu札记 64位kubuntu札记 统计软件R Virtualbox stardict星际译王 Ubuntu重装windows系统后的grub引导修复 SSH服务及花生壳域名解析 采用cbp2make工具由code::blocks工程创建makefile文件 UBUNTU 札记

Tips for Windows

2019年08月01日

OpenSSH for Windows

Refer to this post for enable OpenSSH server on Windows.

# Find the Optional Features 
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'

# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

# Start the sshd service
Start-Service sshd

# OPTIONAL but recommended:
Set-Service -Name sshd -StartupType 'Automatic'

# Confirm the Firewall rule is configured. It should be created automatically by setup. Run the following to verify
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
    Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
    Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
}

# Set the default launched shell as PowerShell in Windows registry
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force`

Try login with like ssh tunnel\\administrator@127.0.0.1. The public key should be appended into C:\ProgramData\ssh\administrators_authorized_keys, see details here.

Visual Studio

  • Shortcuts & Options

    Key Usage
    Ctrl+, smart search
    F12 go to definition
    Shift+F12 find all reference
    Window->Reset Window Layout mess-upped windows
  • Disable the MFC dll symbol loading when debugging: Debug->Options=>Debugging->Symbols

  • Remove the debugger symbol file named *.pdb, usually in the same folder with binary to be debugged, to avoid error The source file is different from when the module was build.

  • Remove the folder .vs beside the solution file *.sln to fix Visual Studio introduced error, like IntelliSense not finding some file.

  • Watch an array with the start pointer p followed by the number of elements, e.g. p,10 to view {p[0],p[1],...,p[9]}

  • The Immediate Window can be used to inspect some values in debug mode. With the powerful AutoHotKey script as following, one can inspect an array.
      #z:: ; press Win+Z to run this script
      Loop, 16
          {
              Send array[%A_Index%-1]{enter}
              Sleep, 100
          }
      return
    
  • Using Snippet Designer to quickly insert code. At first search and install it in Tool => Extensions and Updates, then right click on any code piece to Export as Snippet. Or View => Other Windows => Snippet Explorer to view/modify existing snippets. The snippet will be transformed into XML which saved under like C:\Users\${UserName}\Documents\Visual Studio 2015\Code Snippets\Visual C++\My Code Snippets.

Visual Studio Code

  • Note: Press Ctrl+, to open VS settings and then search term eol, change the default end of line to \n(LF) to be consistent with Linux system.

  • CMD+K+CMD+0/1/2/3 to fold and CMD+K+CMD+J to unfold. Useful in markdown; CMD under windows should be Ctrl.

Powershell

Introduction

Powershell is the next generation of command line interface for Windows and Linux/Unix system. The biggest difference between Powershell and normal shell is that it pass objects instead of pure text information when piping. Powershell is a cross-platform language, and it has build-in .Net object system.

See following short script as an example to peek the super power of Powershell, it is used to convert all slides under a directory into bunch of PNG files. Try save it as convert-PPT2PNGs.ps1 and run.

Function Convert-pptx2pngs{
    [CmdletBinding()]
    Param($File, $OutputFile)

    Add-Type -AssemblyName office -ErrorAction SilentlyContinue
    # Add-Type -AssemblyName microsoft.office.interop.powerpoint -ErrorAction SilentlyContinue

    $ppt = New-Object -com powerpoint.application
    # $ppt.Visible = [Microsoft.Office.Core.MsoTriState]::msoFalse

    $opt = [Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType]::ppSaveAsPNG
    $pres = $ppt.Presentations.Open($File)
    $pres.SaveAs($OutputFolder+'.pngs', $opt)

    $pres.Close()
    $ppt.Quit()
    $ppt=$null
}

$Folder = "C:\Users\nick\Documents"
Foreach($File in $(Get-ChildItem $Folder -Recurse -Include *.ppt,*pptx)){
    $OutputFolder = $File.FullName.TrimEnd('.pptx').TrimEnd('.ppt')
    if (Test-Path -Path $OutputFolder) {
        $OutputFolder = $OutputFolder + '_2'
    }

    Write-Output ("Converting " + $File.FullName + " To " + $OutputFolder)
    # $Folder = New-Item -Path $OutputFolder -ItemType Directory
    Convert-pptx2pngs -File $File -OutputFile $OutputFolder
}

Powershell Tips

Examples

> $env:GOPATH = 'C:\go' # set envionment variable

Error message “running scripts is disabled

Enable ability to execute .ps1 scripts in powershell with command Set-ExecutionPolicy -Scope CurrentUser Unrestricted.

Install powershell in Ubuntu

To be noticed, the command named as pwsh in Ubuntu.

# download and import the public key
curl -k https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

# import the source list 
curl -k https://packages.microsoft.com/config/ubuntu/18.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list
# if apt is using a Proxy, need to change the source from `https` to `http` or error might happen

# finally update and install
sudo apt update && sudo apt install powershell

WSL2

Installation

  1. Search Turn Windows features on or off(just type to search after hit Win) and then check the term Windows Subsystem for Linux(system reboot may needed).

  2. Install the Linux subsystem which ever you like with wsl.exe --install -d <Distribution Name>. Or import a Linux filesystem with LxRunOffline

  • First extract the tar file install.tar from like the offcial *Ubuntu18.04onWindows*.Appx file (open with Winzip)
  • Type command X:\path\to\LxRunOffline.exe install -n ANY_NAME_like_ubuntu -d C:\path\to\where\your\want\to\store\ubuntu\ -f C:\path\to\the\install.tar -s in Powershell with administrator permission to install the distribution.
  1. In CMD or PowerShell just type in wsl will enter the bash. Or run command X:\path\to\LxRunOffline.exe run -w -n "ubuntu" if manually imported(or click the shortcut on Desktop, created by option -s when importing.)

Tips

  • The C: drive will be automatically mount under /mnt.

  • Use command like echo "copy to Win10 clipboard" | clip.exe and powershell.exe -command "Get-Clipboard" | tee save/to/WSL/file to synchronize clipboard.

Windows do not have the ability to list all dependend dll files of one excutable file like ldd command on Linux. One similar utility is dumpbin under Microsoft Visual Studio developer command prompt. One can use following python3 script to list the dependencied recursively.

#!/usr/bin/env python3

import subprocess
import os
import logging


def ldd_one(path: str):
    res = subprocess.run(["dumpbin", "/dependents", path], capture_output=True)

    if res.returncode!=0:
        return []

    deps = []
    start = False
    for l in res.stdout.split(b'\r\n'):
        if l.strip()==b'':
            continue

        if start==False and l.find(b'Image has the following dependencies')>=0:
            start = True
            continue

        if l.find(b'Summary')>=0:
            break

        p = l.strip().decode()
        if os.path.exists(p):
            deps.append(p)

    return deps

def main():
    all_deps = ["start.exe"]
    n_deps = 0

    while True:
        new_deps = {}
        for i in all_deps[n_deps:]:
            new_deps = {*new_deps, *ldd_one(i)}

        new_deps = new_deps-set(all_deps)
        logging.debug(new_deps)
        if len(new_deps)==0:
            break

        n_deps = len(all_deps)
        all_deps.extend(new_deps)

    for i in all_deps:
        print(f"'{i}'")


if __name__ == '__main__':
    main()

Useful Software

  • cmder
    • Import this configure file
    • Then Win+Alt+L can be used to move the Cmder to next monitor.
  • Multi-tab File Explorer enhancement QTTabBar or this forked version

  • tigervnc
    • Press F8(default) to get the viewer options window, which contains exit fullscreen choice.
    • Start and stop the vncserver under Linux system with vncserver -geometry 1920x1200 :${DISPLAY_ID-1} and vncserver -kill :${DISPLAY_ID-1}
    • Create a shortcut with target like D:\path\to\vncviewer-1.12.0.exe --PasswordFile=X:\.vnc\passwd 192.168.1.8::5901 for access desktop instance without input password. The passwd file is generated in Linux and maybe mapped to driver X: from samba service.
  • NoMachine for remote desktop
    • Share the ssh public key for no-password login ln -s $HOME/.ssh/authorized_keys ~/.nx/config/authorized.crt
  • Snipaste for screenshot

  • WinDirStat like ncdu in Linux for Disk usage analysis

  • AutoHotkey for automation on Windows

  • MSYS2 based on Cygwin for building native Windows software. Command pacman -Sy to refresh package repo and pacman -S ncdu to install new softwares.

Reference